編輯:關於 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 才會「真正」響應外部點擊——也就是點擊彈窗外部或按返回鍵時才會消失。少了背景設定,外部觸摸事件不會被處理。
預設情況下 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 只有一個參數,指向一個樣式資源,因此我們需要定義動畫檔與樣式。
先做一個由上滑入、下滑出的動畫:
<!-- 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
一步集成側滑刪除菜單:SwipeDelMenuLayout 使用與原理
專案地址:https://github.com/mcxtzhang/SwipeDelMenuLayout (覺得不錯的話,歡迎隨手點個 star。) 先講最重要的一句話
Android Path 與 PathMeasure 進階用法完整解析
一、前言 在先前探討「路徑與文字」的內容裡,我們已經掌握了 Path 的基礎操作。本篇則會補充上一回未談到的進階議題,重點放在 Path 的幾個關鍵方法,接著延伸到 Pa
用 TeamViewer 從 Android 手機遠端控制你的電腦
TeamViewer 是一套能在任何防火牆與 NAT 代理背後運作的遠端控制方案,涵蓋桌面共享與檔案傳輸,設定簡單、連線速度快。要連上另一台電腦,只需在兩端同時執行 Te
Android 設計模式筆記(二):觀察者模式的四個角色與實作
觀察者模式有時也被稱為發布/訂閱模式。它定義了一種一對多的依賴關係,讓多個觀察者物件同時監聽同一個主題物件;當主題的狀態發生變化時,會主動通知所有觀察者,使它們能夠自動更