Android中PopupWindow显示在指定位置

本文转自:http://www.open-open.com/lib/view/open1338651415953.html

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显示在正下方,这正是我们所需要的,对称是一种美啊。

/uploads/allimg/130323/2134361638-0.png

代码实现的关键是点击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的正下方显示,此处的单位是pixels
    int xoffInPixels = ScreenTools.getInstance(PopDemoActivity.this).getWidth() / 2 - titleName.getWidth() / 2;
    // 将pixels转为dip
    int 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();
        }
    });
}