1. 程式人生 > >Android中PopupWindow顯示在指定位置

Android中PopupWindow顯示在指定位置

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();
        }
                               
    });
                                   
}