Android中PopupWindow位置的确定一般通过showAsDropDown函数来实现,该函数有两个重载函数,分别定义如下:

    public void showAsDropDown(View anchor) {        showAsDropDown(anchor, 0, 0);    }    public void showAsDropDown(View anchor, int xoff, int yoff) {        if (isShowing() || mContentView == null) {            return;        }        registerForScrollChanged(anchor, xoff, yoff);        mIsShowing = true;        mIsDropdown = true;        WindowManager.LayoutParams p = createPopupLayout(anchor.getWindowToken());        preparePopup(p);        updateAboveAnchor(findDropDownPosition(anchor, p, xoff, yoff));        if (mHeightMode < 0) p.height = mLastHeight = mHeightMode;        if (mWidthMode < 0) p.width = mLastWidth = mWidthMode;        p.windowAnimations = computeAnimationResource();        invokePopup(p);    }

也就是说,调用第一个函数时,x和y坐标偏移量默认是0,此时PopupWindow显示的结果如下中图所示。而要实现PopupWindow显示在wenwen的正下方时,就需要程序员自己进行坐标偏移量的计算,下右图所示,当点击wenwen时,PopupWindow显示在正下方,这正是我们所需要的,对称是一种美啊。




代码实现的关键是点击wenwen后的响应函数,此处直接上代码,不废话了:

public void onClick(View v) {LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);ViewGroup menuView = (ViewGroup) mLayoutInflater.inflate(R.layout.tips, null, true);pw = new PopupWindow(menuView, LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, true);  // 设置点击返回键使其消失,且不影响背景,此时setOutsideTouchable函数即使设置为false// 点击PopupWindow 外的屏幕,PopupWindow依然会消失;相反,如果不设置BackgroundDrawable// 则点击返回键PopupWindow不会消失,同时,即时setOutsideTouchable设置为true// 点击PopupWindow 外的屏幕,PopupWindow依然不会消失pw.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); pw.setOutsideTouchable(false); // 设置是否允许在外点击使其消失,到底有用没?pw.setAnimationStyle(R.style.PopupAnimation); // 设置动画// 计算x轴方向的偏移量,使得PopupWindow在Title的正下方显示,此处的单位是pixelsint xoffInPixels = ScreenTools.getInstance(PopDemoActivity.this).getWidth() / 2 - titleName.getWidth() / 2;// 将pixels转为dipint xoffInDip = ScreenTools.getInstance(PopDemoActivity.this).px2dip(xoffInPixels);pw.showAsDropDown(titleName, -xoffInDip, 0);//pw.showAsDropDown(titleName);pw.update();TextView tv = (TextView) menuView.findViewById(R.id.tips_ok);tv.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {pw.dismiss();}});}



更多相关文章

  1. Android深入浅出之Audio
  2. Android下setLatestEventInfo警告、Handler警告、SimpleDateForm
  3. Android(安卓)创建SQLite数据库(一)
  4. Android开发环境的搭建步骤
  5. Android黑科技 自动点击
  6. Android(安卓)圆角 填充 边框
  7. android Button组件的属性和方法
  8. android textview 自动链接网址 修改默认点击事件
  9. 箭头函数的基础使用

随机推荐

  1. android超快模拟器Ggenymotion的安装和配
  2. android复制数据库到SD卡
  3. Android热插拔事件处理流程--Vold
  4. Android installation problem on Ubuntu
  5. Android getText(int resId)和getString(
  6. 获取Android设备的方向
  7. Android显示一个文本框的内容
  8. Android开发之屏幕属性
  9. Android(安卓)Application Framework FAQ
  10. Android Studio修改默认Activity继承AppC