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

用 PopupWindow 加 GridView 打造 UCWeb 風格的功能菜單

編輯:關於 Android 程式設計

UCWeb 的底部彈出菜單相當有辨識度:半透明遮罩蓋住整個畫面,功能圖示以四欄網格排列,點選後菜單收起。這個效果不需要任何特殊元件,用 PopupWindow 裝一個 GridView 就能完成。

實作思路

  1. 保留實體 menu 鍵(或選單按鈕)的作用,作為菜單的觸發點。
  2. 用 PopupWindow 作為菜單的顯示容器,它天生具備「浮在當前 Activity 之上」與「點擊外部自動關閉」的能力。
  3. 用 GridView 排列所有子菜單項目。

一、布局檔

popupwindow.xml——外層 LinearLayout 使用半透明黑作為遮罩,內部再放一個固定尺寸的容器裝 GridView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:background="#50000000"
    android:layout_height="fill_parent"
    android:gravity="bottom|center_horizontal">

    <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
        android:layout_width="320dip"
        android:background="@drawable/bkg2"
        android:id="@+id/popdialog"
        android:layout_height="250dip"
        android:gravity="center_vertical|center_horizontal" >

        <GridView android:id="@+id/gridview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:numColumns="4"
            android:verticalSpacing="10dip"
            android:horizontalSpacing="10dip"
            android:stretchMode="columnWidth"
            android:gravity="center" />
    </LinearLayout>
</LinearLayout>

item_menu.xml——圖示在上、文字在下的標準項目:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout_Item"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingBottom="5dip">

    <ImageView android:id="@+id/item_image"
        android:layout_centerHorizontal="true"
        android:layout_width="40dip"
        android:layout_height="40dip" />

    <TextView android:layout_below="@id/item_image"
        android:id="@+id/item_text"
        android:layout_centerHorizontal="true"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="選項" />
</RelativeLayout>

二、建立 PopupWindow 容器

View view = this.getLayoutInflater().inflate(R.layout.popwindowdemo, null);
pop = new PopupWindow(view, 320, 450);       // 正式專案建議依螢幕尺寸動態計算
pop.setOutsideTouchable(false);
pop.setBackgroundDrawable(new BitmapDrawable());
pop.setFocusable(true);                      // 少了這行,Grid 不會回應 ItemClick
pop.setTouchInterceptor(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        // 點到 gridview 以外的區域時關閉菜單
        if (event.getY() < 240) {
            if (pop.isShowing()) pop.dismiss();
        }
        return false;
    }
});

setFocusable(true) 是這段程式碼裡最容易被漏掉的一行。少了它,PopupWindow 不會取得焦點,GridView 的 OnItemClickListener 完全不會觸發,症狀是「菜單看起來正常但點了沒反應」,很容易誤判為 Adapter 的問題。

三、初始化 GridView 與資料

int[] menu_image_array = {
    R.drawable.menu_search, R.drawable.menu_filemanager, R.drawable.menu_downmanager,
    R.drawable.menu_fullscreen, R.drawable.menu_inputurl, R.drawable.menu_bookmark,
    R.drawable.menu_bookmark_sync_import, R.drawable.menu_sharepage, R.drawable.menu_quit,
    R.drawable.menu_nightmode, R.drawable.menu_refresh, R.drawable.menu_more
};

String[] menu_name_array = {
    "搜索", "文件管理", "下載管理", "全屏", "網址", "書簽",
    "加入書簽", "分享頁面", "退出", "夜間模式", "刷新", "更多"
};

private SimpleAdapter getMenuAdapter(String[] menuNameArray, int[] imageResourceArray) {
    ArrayList data = new ArrayList();
    for (int i = 0; i < menuNameArray.length; i++) {
        HashMap map = new HashMap();
        map.put("itemImage", imageResourceArray[i]);
        map.put("itemText", menuNameArray[i]);
        data.add(map);
    }
    return new SimpleAdapter(this, data, R.layout.item_menu,
            new String[] { "itemImage", "itemText" },
            new int[] { R.id.item_image, R.id.item_text });
}

menuGrid = (GridView) view.findViewById(R.id.gridview);
menuGrid.setAdapter(getMenuAdapter(menu_name_array, menu_image_array));

SimpleAdapter 在這裡很合適:資料只是「圖 + 字」的靜態對照表,不需要自定义 BaseAdapter。map 的 key 對應 item_menu.xml 中的 view id,這種映射寫法比繼承 BaseAdapter 精簡許多。

四、註冊選單彈起事件

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    pop.showAtLocation(findViewById(R.id.mainfrm), Gravity.CENTER | Gravity.BOTTOM, 0, 0);
    return false;      // 回傳 false 表示不使用系統預設的選單面板
}

回傳 false 是關鍵:若回傳 true,系統會同時顯示原生選單,變成兩個菜單疊在一起。

五、註冊項目點擊

menuGrid.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
        Toast.makeText(UIMenu.this, "Click" + arg2, Toast.LENGTH_SHORT).show();
        if (pop.isShowing()) pop.dismiss();     // 選完就收起菜單
    }
});

畫面如下:

幾點值得調整的地方

  • 尺寸別寫死:範例中的 320×450 是硬編碼,在不同解析度上會比例失衡。改用螢幕寬高的百分比計算會穩健得多。
  • 點擊外部關閉的判斷:用 event.getY() 與固定數字比較雖然能用,但更可靠的方式是檢查被點擊的 view 是否為 popdialog 容器本身。
  • 視窗背景不可為 null:setBackgroundDrawable 若傳入 null,PopupWindow 在部分版本上會直接崩潰,這裡傳一個空的 BitmapDrawable 是常見解法。
  • 菜單項目最好用 enum 或常數管理:範例用 position 當作識別碼,項目一多就容易錯位;實務上會在資料結構裡帶一個 action 欄位,點擊時直接 switch。
  • 生命週期清理:Activity 銷毀前呼叫 pop.dismiss(),避免視窗洩漏。

整體來說,PopupWindow + GridView 這個組合可以視為「浮動層 + 資料容器」的通用範式,替換成 ListView、RecyclerView 或自訂布局同樣成立,是打造各種浮動面板的起手式。

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