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

Android 用 PopupWindow 實現自定義下拉菜單

編輯:關於 Android 程式設計

做頂部右側的下拉菜單時,第一反應通常是 Spinner。但 Spinner 樣式固定、可定制性有限,一旦設計稿要求圓角背景、圖標加文字混排、自定義字號顏色,它就不夠用了。這時候 PopupWindow 是更好的選擇:本質上就是一個浮在你指定控件附近的容器,裡面想放什麼佈局都可以。

第一步:自定義菜單佈局

以「掃一掃 / 我的二維碼」為例,用圓角背景包住兩個可點擊行,中間加分隔線:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="110dp"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_circle_drop_down_qr_code"
        android:orientation="vertical"
        android:layout_marginRight="@dimen/padding_10"
        android:paddingBottom="0dp"
        android:paddingLeft="@dimen/padding_5"
        android:paddingRight="@dimen/padding_5"
        android:paddingTop="@dimen/padding_5">

        <LinearLayout
            android:id="@+id/lin_scan_qr_code"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="horizontal"
            android:paddingBottom="@dimen/padding_5"
            android:paddingTop="@dimen/padding_5">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_circle_scan_qr_code" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/padding_10"
                android:gravity="center"
                android:text="掃一掃"
                android:textColor="@color/color_white"
                android:textSize="@dimen/text_16" />
        </LinearLayout>

        <View
            android:layout_width="wrap_content"
            android:layout_height="1px"
            android:layout_marginLeft="@dimen/padding_3"
            android:layout_marginRight="@dimen/padding_3"
            android:background="@color/color_white" />

        <LinearLayout
            android:id="@+id/lin_my_qr_code"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="horizontal"
            android:paddingBottom="@dimen/padding_5"
            android:paddingTop="@dimen/padding_5">

            <ImageView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_circle_my_qr_code" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="@dimen/padding_10"
                android:gravity="center"
                android:text="二維碼"
                android:textColor="@color/color_white"
                android:textSize="@dimen/text_16" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

第二步:代碼中創建 PopupWindow

// 獲取自定義佈局的 View
View customView = getActivity().getLayoutInflater()
        .inflate(R.layout.lay_circle_pop_drop_down_qr_code, null, false);

// 創建 PopupWindow 實例,寬 110dp(/dp 換算),高隨內容自適應
mQrCodePopWindow = new PopupWindow(customView,
        CommonUtil.dipToPx(getContext(), 110),
        ViewGroup.LayoutParams.WRAP_CONTENT, true);

// 如需進場動畫,打開下面這行(R.style.AnimationFade 需事先定義)
// mQrCodePopWindow.setAnimationStyle(R.style.AnimationFade);

// 綁定菜單項點擊事件
customView.findViewById(R.id.lin_scan_qr_code).setOnClickListener(v -> {
    ToastUtil.show(getContext(), "掃一掃");
    dismissQrCodePopWindow();
});

customView.findViewById(R.id.lin_my_qr_code).setOnClickListener(v ->
        ToastUtil.show(getContext(), "二維碼"));

這裡有個必須注意的細節:構造函數最後那個 true 是 setFocusable。如果想要「點擊空白處自動關閉菜單」,setFocusable(true) 和 setBackgroundDrawable() 兩者缺一不可——這是實測結論。原因是 PopupWindow 只有獲得焦點才會接收返回鍵與外部觸摸事件,而非空背景才能讓外部區域的點擊被判定為「窗外」。所以即使你不需要自定義背景,也要給一個空的 BitmapDrawable:

mQrCodePopWindow.setBackgroundDrawable(new BitmapDrawable());

第三步:控制顯示與隱藏

給觸發控件加點擊事件,用 showAsDropDown() 讓菜單錨定在它下方:

@OnClick(R.id.lin_top_right)
public void onClick(View v) {
    if (mQrCodePopWindow != null && mQrCodePopWindow.isShowing()) {
        mQrCodePopWindow.dismiss();
    } else {
        initQrCodePopWindow();
        mQrCodePopWindow.showAsDropDown(v);
    }
}

幾個實用補充

定位方式。 除了 showAsDropDown(view)(錨定在控件下方),還有 showAtLocation(view, gravity, x, y)(相對於窗口定位),以及帶偏移量的 showAsDropDown(view, xoff, yoff) 版本,可以用來微調菜單與觸發按鈕的間距。

動畫。 想加進出動畫,除了 setAnimationStyle(),也可以在 showAsDropDown 前後配合 ObjectAnimator 做透明度與 translationY 過渡,效果往往比預設樣式更貼合設計稿。

內存。 Activity 銷毀前記得 dismiss(),否則窗口洩露會直接導致 WindowLeaked 報錯。

替代方案。 如果只是簡單的幾個選項,PopupMenu 或 ListPopupWindow 寫起來更省事;一旦需要圖標、副標題、自定義分割線這類設計,回到 PopupWindow 才是正解。

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