Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 模仿 UCWeb 菜單效果:PopupWindow 搭配 GridView 實作

編輯:Android 開發實例

UCWeb 那個半透明、置底彈出的九宮格菜單看起來很不錯,自己做一個也不難。整體思路是:

  1. 保留實體 Menu 鍵的作用(讓它負責彈出菜單)
  2. 用 PopupWindow 當菜單的顯示容器
  3. 用 GridView 排列所有子項目

一、版面檔

popupwindow.xml:

<?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>

外層 LinearLayout 鋪了半黑的背景色(#50000000),作用是做出「菜單彈出時背景變暗」的效果,這是讓彈出層有層次感的關鍵細節。內層則是實際的菜單面板,置中靠下。

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">
    </ImageView>
    <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();
        }
        Log.d("Demo", "popupWindow::onTouch >>> view: " + v + ", event: " + event);
        return false;
    }
});

這幾行裡有兩個容易忽略的設定:

setFocusable(true) 是必須的。少了它,PopupWindow 不會取得焦點,GridView 的點擊事件根本不會觸發——症狀是「菜單彈得出來但點了沒反應」,很難往焦點這方向想。

setTouchInterceptor 實作的是「點空白處關閉」。用寫死座標(event.getY() < 240)來判斷有沒有點到面板外,實務上很脆弱——換個螢幕尺寸就失效。比較穩健的做法是為面板本身掛一個吃掉事件的監聽器,讓事件只在面板外才落到 interceptor 上。

三、初始化 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 = {
    "搜索", "文件管理", "下載管理", "全屏", "網址", "書簽",
    "加入書簽", "分享頁面", "退出", "夜間模式", "刷新", "更多"
};

/**
 * 建立菜單 Adapter
 *
 * @param menuNameArray      名稱陣列
 * @param imageResourceArray 圖片資源陣列
 * @return SimpleAdapter
 */
private SimpleAdapter getMenuAdapter(String[] menuNameArray, int[] imageResourceArray) {
    ArrayList<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
    for (int i = 0; i < menuNameArray.length; i++) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("itemImage", imageResourceArray[i]);
        map.put("itemText", menuNameArray[i]);
        data.add(map);
    }
    SimpleAdapter simperAdapter = new SimpleAdapter(this, data, R.layout.item_menu,
            new String[] { "itemImage", "itemText" },
            new int[] { R.id.item_image, R.id.item_text });
    return simperAdapter;
}

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

用 SimpleAdapter 的好處是不必自訂 Adapter 類別:把資料整理成 List<Map>,再用兩個平行陣列分別指定「map 的 key」與「要填進哪個 View 的 id」,它就會自動對應。這種「圖 + 文」的簡單清單,SimpleAdapter 是最省事的选择。

四、註冊 Menu 彈起事件

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    pop.showAtLocation(findViewById(R.id.mainfrm), Gravity.CENTER | Gravity.BOTTOM, 0, 0);
    return false; // 不回傳 super.onCreateOptionsMenu(menu)
}

回傳 false 是刻意的:告訴系統「我已經自己處理了菜單顯示,你不需要再畫標準選單」。

五、註冊子項目點擊事件

menuGrid.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
        Log.v("Demo", "menuGrid.setOnItemClickListener: " + arg2 + " " + arg3);
        Toast.makeText(UIMenu.this, "Click" + arg2, Toast.LENGTH_SHORT).show();
        if (pop.isShowing()) {
            pop.dismiss(); // 關閉菜單
        }
    }
});

六、成果

七、可以再改進的地方

尺寸寫死是這個實作最明顯的問題。new PopupWindow(view, 320, 450) 裡的數字依裝置而異,換一台手機就可能超出畫面或被裁切。正確做法是以螢幕實際寬高為基準做比例換算,或直接傳 MATCH_PARENT 搭配版面檔的 gravity 控制位置。

另一個可以調整的是菜單的呈現方式。這個實作把 Menu 鍵「劫持」成自訂彈出層,在早期實體 Menu 鍵仍是標準配備的年代很合理。但在新版的 Android 上(實體 Menu 鍵已消失、系統會以三個點的 overflow 選單呈現),比較通用的做法是直接把自訂面板綁到 Toolbar 的 overflow 按鈕上,讓使用者不必依賴任何硬體按鍵就能叫出菜單。

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