Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

PopupWindow 使用要點整理:顯示位置、動畫與背景變暗

編輯:關於 Android 程式設計

前幾天要用 PopupWindow,一時想不起怎麼寫,上網查完自己做了個 demo,順手把要點記錄下來。

使用場景

顧名思義,PopupWindow 就是浮動彈窗。ActionBar / Toolbar 的溢出選單、一組選項的容器、清單形式的浮層,都很常見。

基本三步驟

使用 PopupWindow 可以歸納為三步:建立實例、設定背景與事件監聽(可選但實務上幾乎都會做)、顯示它。

// PopupWindow 的內容 View
View contentView = LayoutInflater.from(context).inflate(layoutRes, null, false);
// 建立 PopupWindow:依序為內容 View、寬、高、是否可獲取焦點
PopupWindow window = new PopupWindow(contentView, 100, 100, true);
// 設定背景
window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
// 是否響應外部觸摸事件
window.setOutsideTouchable(true);
// 是否響應內部觸摸事件
window.setTouchable(true);
// 相對於錨點顯示:錨點 View、x 偏移、y 偏移
window.showAsDropDown(anchor, xoff, yoff);
// 或者相對於父容器顯示:父 View、位置、x 偏移、y 偏移
// window.showAtLocation(parent, gravity, x, y);

這裡有兩行特別容易踩坑:

window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
window.setOutsideTouchable(true);

只有同時設定了背景且允許響應外部觸摸,PopupWindow 才會「真正」響應外部點擊——也就是點擊彈窗外部或按返回鍵時才會消失。少了背景設定,外部觸摸事件不會被處理。

用 showAsDropDown 控制顯示位置

預設情況下 PopupWindow 顯示在錨點的左下方。若想讓它出現在錨點上方或居中,就得靠 showAsDropDown 的 xoff 與 yoff 兩個參數。這裡我們把需求擴充成水平與垂直各五種,共 25 種組合。

水平方向:

ALIGN_LEFT:錨點內部左側;
ALIGN_RIGHT:錨點內部右側;
CENTER_HORI:錨點水平居中;
TO_RIGHT:錨點外部右側;
TO_LEFT:錨點外部左側。

垂直方向:

ALIGN_ABOVE:錨點內部上方;
ALIGN_BOTTOM:錨點內部下方;
CENTER_VERT:錨點垂直居中;
TO_BOTTOM:錨點外部下方;
TO_ABOVE:錨點外部上方。

先封裝一個 CommonPopupWindow 基類:

public abstract class CommonPopupWindow {
    protected Context context;
    protected View contentView;
    protected PopupWindow mInstance;

    public CommonPopupWindow(Context c, int layoutRes, int w, int h) {
        context = c;
        contentView = LayoutInflater.from(c).inflate(layoutRes, null, false);
        initView();
        initEvent();
        mInstance = new PopupWindow(contentView, w, h, true);
        initWindow();
    }

    public View getContentView() { return contentView; }
    public PopupWindow getPopupWindow() { return mInstance; }

    protected abstract void initView();
    protected abstract void initEvent();

    protected void initWindow() {
        mInstance.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        mInstance.setOutsideTouchable(true);
        mInstance.setTouchable(true);
    }

    public void showBashOfAnchor(View anchor, LayoutGravity layoutGravity, int xmerge, int ymerge) {
        int[] offset = layoutGravity.getOffset(anchor, mInstance);
        mInstance.showAsDropDown(anchor, offset[0] + xmerge, offset[1] + ymerge);
    }

    public void showAsDropDown(View anchor, int xoff, int yoff) {
        mInstance.showAsDropDown(anchor, xoff, yoff);
    }

    public void showAtLocation(View parent, int gravity, int x, int y) {
        mInstance.showAtLocation(parent, gravity, x, y);
    }
}

重點是 showBashOfAnchor,其中的 LayoutGravity 參數負責決定相對錨點的位置。接著定義 LayoutGravity:

public static class LayoutGravity {
    private int layoutGravity;
    // 注意:這些常數的順序不可任意調整
    public static final int ALIGN_LEFT   = 0x1;
    public static final int ALIGN_ABOVE  = 0x2;
    public static final int ALIGN_RIGHT  = 0x4;
    public static final int ALIGN_BOTTOM = 0x8;
    public static final int TO_LEFT      = 0x10;
    public static final int TO_ABOVE     = 0x20;
    public static final int TO_RIGHT     = 0x40;
    public static final int TO_BOTTOM    = 0x80;
    public static final int CENTER_HORI  = 0x100;
    public static final int CENTER_VERT  = 0x200;

    public LayoutGravity(int gravity) { layoutGravity = gravity; }
    public int getLayoutGravity() { return layoutGravity; }
    public void setLayoutGravity(int gravity) { layoutGravity = gravity; }

    public void setHoriGravity(int gravity) {
        layoutGravity &= (0x2 + 0x8 + 0x20 + 0x80 + 0x200);
        layoutGravity |= gravity;
    }
    public void setVertGravity(int gravity) {
        layoutGravity &= (0x1 + 0x4 + 0x10 + 0x40 + 0x100);
        layoutGravity |= gravity;
    }
    public boolean isParamFit(int param) { return (layoutGravity & param) > 0; }

    public int getHoriParam() {
        for (int i = 0x1; i <= 0x100; i = i << 2) if (isParamFit(i)) return i;
        return ALIGN_LEFT;
    }
    public int getVertParam() {
        for (int i = 0x2; i <= 0x200; i = i << 2) if (isParamFit(i)) return i;
        return TO_BOTTOM;
    }

    public int[] getOffset(View anchor, PopupWindow window) {
        int anchWidth = anchor.getWidth();
        int anchHeight = anchor.getHeight();
        int winWidth = window.getWidth();
        int winHeight = window.getHeight();
        View view = window.getContentView();
        if (winWidth <= 0) winWidth = view.getWidth();
        if (winHeight <= 0) winHeight = view.getHeight();

        int xoff = 0, yoff = 0;
        switch (getHoriParam()) {
            case ALIGN_LEFT:   xoff = 0; break;
            case ALIGN_RIGHT:  xoff = anchWidth - winWidth; break;
            case TO_LEFT:      xoff = -winWidth; break;
            case TO_RIGHT:     xoff = anchWidth; break;
            case CENTER_HORI:  xoff = (anchWidth - winWidth) / 2; break;
            default: break;
        }
        switch (getVertParam()) {
            case ALIGN_ABOVE:  yoff = -anchHeight; break;
            case ALIGN_BOTTOM: yoff = -winHeight; break;
            case TO_ABOVE:     yoff = -anchHeight - winHeight; break;
            case TO_BOTTOM:    yoff = 0; break;
            case CENTER_VERT:  yoff = (-winHeight - anchHeight) / 2; break;
            default: break;
        }
        return new int[]{ xoff, yoff };
    }
}

getOffset 會依水平與垂直方向的 gravity 計算出最終偏移量。使用時透過 setHoriGravity 與 setVertGravity 分別設定,或直接建立 LayoutGravity 實例。

實際效果:

用 setAnimationStyle 加入動畫

預設的彈出與消失過於生硬,加一點進出動畫體驗會好很多。setAnimationStyle 只有一個參數,指向一個樣式資源,因此我們需要定義動畫檔與樣式。

先做一個由上滑入、下滑出的動畫:

<!-- res/anim/translate_in.xml -->
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="0"
               android:fromYDelta="100%" android:toYDelta="0"
               android:duration="200" />
</set>
<!-- res/anim/translate_out.xml -->
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="0" android:toXDelta="0"
               android:fromYDelta="0" android:toYDelta="100%"
               android:duration="200" />
</set>

再定義動畫樣式:

<!-- res/values/styles.xml -->
<style name="animTranslate">
    <item name="android:windowEnterAnimation">@anim/translate_in</item>
    <item name="android:windowExitAnimation">@anim/translate_out</item>
</style>

套用方式:

window.setAnimationStyle(R.style.animTranslate);

(由於動畫時長只有 200ms,加上轉 GIF 時擷取頻率偏低,滑動感不明顯,建議直接跑 demo 觀看。)

彈出時讓背景變暗

加了動畫之後還有個問題:彈窗與背景的層次不夠分明。可以在彈窗顯示後壓暗背景,關閉時還原:

window.setOnDismissListener(new PopupWindow.OnDismissListener() {
    @Override
    public void onDismiss() {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 1.0f;
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }
});
window.showAtLocation(activityPopup, Gravity.BOTTOM, 0, 0);
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.alpha = 0.3f;
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
getWindow().setAttributes(lp);

這樣彈窗的層次就清楚多了。此外還實作了透明度、縮放與旋轉三種動畫樣式,做法大同小異,不再贅述。

原始碼

上述所有程式碼(含未列出的部分)已上傳:https://github.com/jzyhywxz/PopupWindow

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved