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

用 PopupWindow 打造工具欄下拉菜單的完整實作

編輯:關於 Android 程式設計

一、需求與成品預覽

本文示範如何點擊頂部工具欄上的按鈕,向下彈出一份下拉式菜單。工具欄分成左、中、右三個入口,各自對應一份獨立的菜單清單。

二、主介面布局

activity_main.xml 以 RelativeLayout 為骨架,頂部橫幅 rl_topbar 內放三個 TextView:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#897D13"
    tools:context=".MainActivity">

    <RelativeLayout
        android:id="@+id/rl_topbar"
        android:layout_width="match_parent"
        android:layout_height="40dip"
        android:background="#BF7F40"
        android:gravity="center_vertical">

        <TextView
            android:id="@+id/tv_left"
            android:layout_width="70dip"
            android:layout_height="30dip"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dip"
            android:background="@drawable/btn_selector_pop"
            android:clickable="true"
            android:gravity="center"
            android:text="left"
            android:textColor="@android:color/white"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/tv_middle"
            android:layout_width="70dip"
            android:layout_height="30dip"
            android:layout_centerHorizontal="true"
            android:background="@drawable/btn_selector_pop"
            android:clickable="true"
            android:gravity="center"
            android:text="middle"
            android:textColor="@android:color/white"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/tv_right"
            android:layout_width="70dip"
            android:layout_height="30dip"
            android:layout_alignParentRight="true"
            android:layout_marginRight="10dip"
            android:background="@drawable/btn_selector_pop"
            android:clickable="true"
            android:gravity="center"
            android:text="right"
            android:textColor="@android:color/white"
            android:textSize="16sp" />
    </RelativeLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Drop-down"
        android:textColor="@android:color/white"
        android:textSize="20sp" />
</RelativeLayout>

三、Activity 邏輯

三個入口的做法幾乎一致,因此把重複的部分收斂成一個共用方法,可讀性會好很多:

public class MainActivity extends Activity {

    private RelativeLayout rlTopBar;
    private TextView tvLeft, tvMiddle, tvRight;
    private PopupWindow popLeft, popMiddle, popRight;
    private final List<Map<String, String>> listLeft = new ArrayList<>();
    private final List<Map<String, String>> listMiddle = new ArrayList<>();
    private final List<Map<String, String>> listRight = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rlTopBar = (RelativeLayout) findViewById(R.id.rl_topbar);
        tvLeft = (TextView) findViewById(R.id.tv_left);
        tvMiddle = (TextView) findViewById(R.id.tv_middle);
        tvRight = (TextView) findViewById(R.id.tv_right);

        buildData(listLeft, "left");
        buildData(listMiddle, "mid");
        buildData(listRight, "right");

        tvLeft.setOnClickListener(myListener);
        tvMiddle.setOnClickListener(myListener);
        tvRight.setOnClickListener(myListener);
    }

    /** 產生 9 筆示範資料 */
    private void buildData(List<Map<String, String>> target, String prefix) {
        for (int i = 1; i < 10; i++) {
            Map<String, String> map = new HashMap<>();
            map.put("item", prefix + i);
            target.add(map);
        }
    }

    /** 建立並顯示下拉視窗 */
    private void showDropDown(TextView anchor, PopupWindow popup,
                              List<Map<String, String>> data) {
        View content = getLayoutInflater().inflate(R.layout.pop_menulist, null);
        ListView listView = (ListView) content.findViewById(R.id.menulist);
        listView.setAdapter(new SimpleAdapter(this, data,
                R.layout.pop_menuitem,
                new String[]{"item"}, new int[]{R.id.menuitem}));

        final PopupWindow window = new PopupWindow(
                content, anchor.getWidth(), LayoutParams.WRAP_CONTENT);
        window.setBackgroundDrawable(new ColorDrawable(0x00000000));
        window.setAnimationStyle(R.style.PopupAnimation);
        window.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        window.setTouchable(true);
        window.setOutsideTouchable(true);
        window.setFocusable(true);
        window.update();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                anchor.setText(((TextView) view.findViewById(R.id.menuitem))
                        .getText().toString());
                if (window.isShowing()) {
                    window.dismiss();
                }
            }
        });

        // 讓菜單緊貼工具欄下緣
        int topBarHeight = rlTopBar.getBottom();
        window.showAsDropDown(anchor, 0,
                (topBarHeight - anchor.getHeight()) / 2);

        window.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    window.dismiss();
                    return true;
                }
                return false;
            }
        });
    }

    private final View.OnClickListener myListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_left:
                    toggle(popLeft, tvLeft, listLeft);
                    break;
                case R.id.tv_middle:
                    toggle(popMiddle, tvMiddle, listMiddle);
                    break;
                case R.id.tv_right:
                    toggle(popRight, tvRight, listRight);
                    break;
                default:
                    break;
            }
        }
    };

    /** 已展開則收合,未展開則彈出 */
    private void toggle(PopupWindow popup, TextView anchor,
                        List<Map<String, String>> data) {
        if (popup != null && popup.isShowing()) {
            popup.dismiss();
            return;
        }
        PopupWindow created = createAnchorWindow(anchor, data);
        if (anchor == tvLeft) popLeft = created;
        else if (anchor == tvMiddle) popMiddle = created;
        else popRight = created;
    }

    private PopupWindow createAnchorWindow(TextView anchor,
                                           List<Map<String, String>> data) {
        View content = getLayoutInflater().inflate(R.layout.pop_menulist, null);
        ListView listView = (ListView) content.findViewById(R.id.menulist);
        listView.setAdapter(new SimpleAdapter(this, data,
                R.layout.pop_menuitem,
                new String[]{"item"}, new int[]{R.id.menuitem}));

        final PopupWindow window = new PopupWindow(
                content, anchor.getWidth(), LayoutParams.WRAP_CONTENT);
        window.setBackgroundDrawable(new ColorDrawable(0x00000000));
        window.setAnimationStyle(R.style.PopupAnimation);
        window.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        window.setTouchable(true);
        window.setOutsideTouchable(true);
        window.setFocusable(true);
        window.update();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                anchor.setText(((TextView) view.findViewById(R.id.menuitem))
                        .getText().toString());
                if (window.isShowing()) window.dismiss();
            }
        });

        int topBarHeight = rlTopBar.getBottom();
        window.showAsDropDown(anchor, 0,
                (topBarHeight - anchor.getHeight()) / 2);
        return window;
    }
}

原理並不複雜:點擊工具欄上的 TextView 後彈出一個 PopupWindow,視窗內容是一個 ListView,逐行呈現菜單項;選中後把文字回寫到工具欄並關閉視窗。

四、彈出視窗與菜單項布局

pop_menulist.xml 只承載一個 ListView:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/shape_bg_pop"
    android:orientation="vertical">

    <ListView
        android:id="@+id/menulist"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:divider="#696969"
        android:dividerHeight="1.0dip"
        android:padding="2dip"
        android:scrollbars="none" />
</LinearLayout>

pop_menuitem.xml 則是單一 TextView 構成的一列:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bg_list_item_pop"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/menuitem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:textColor="@android:color/white"
        android:textSize="16sp" />
</LinearLayout>

五、幾個實作要點

  • PopupWindow 必須設定 BackgroundDrawable,否則點擊外部不會消失。
  • setFocusable(true) 讓視窗取得焦點,才能攔截到外部觸摸事件。
  • showAsDropDown() 的第二、三個參數是相對錨點的偏移量,扣掉半個高度差可讓菜單垂直對齊工具欄底緣。
  • 三個 PopupWindow 建議各自持有參考,才能做到「再點一次收合」的切換效果。

其餘的 shape、selector 等資源檔屬於樣式裝飾,可依專案設計稿自行調整。

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