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

自製 TabMenu 彈出選單:封裝成可重複使用的複合控件

編輯:Android 開發實例

用過 UC 瀏覽器 Android 版的人,大概都對它那個分頁式選單有印象。Android 原生的 OptionsMenu 有個先天限制:超過六項就被折進「更多」裡,能呈現的內容有限。而 Tab-Menu 把選項按分類切成好幾頁,容量大得多,操作也更直覺。

本文示範如何把 TabMenu 做成一個獨立的複合控件,方便直接放進自己的 framework 重複使用。

執行結果:

整體結構

TabMenu 本質上是一個 PopupWindow,裡面垂直堆兩個 GridView:上方是分類標籤列(第一個 GridView),下方是該分類的選項內容(第二個 GridView)。

為了讓彈出與收起有動畫,需要準備三個資源檔。先在 res 下建 anim 目錄:

popup_enter.xml——由下滑入並淡入:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <translate android:fromYDelta="100%p" android:toYDelta="0"
        android:duration="1000" />
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
        android:duration="1000" />
</set>

popup_exit.xml——往下滑出並淡出:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
    <translate android:fromYDelta="0" android:toYDelta="100%p"
        android:duration="1000" />
    <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
        android:duration="1000" />
</set>

values/popup_animation.xml——把兩支動畫綁成一個 style:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="PopupAnimation" parent="android:Animation">
        <item name="android:windowEnterAnimation">@anim/popup_enter</item>
        <item name="android:windowExitAnimation">@anim/popup_exit</item>
    </style>
</resources>

版面檔 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <TextView android:id="@+id/TextView01"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="擴展Menu"></TextView>
</LinearLayout>

TabMenu.java:控件本體

package com.testTabMenu;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout.LayoutParams;

public class TabMenu extends PopupWindow {
    private GridView gvBody, gvTitle;
    private LinearLayout mLayout;
    private MenuTitleAdapter titleAdapter;

    public TabMenu(Context context, OnItemClickListener titleClick,
            OnItemClickListener bodyClick, MenuTitleAdapter titleAdapter,
            int colorBgTabMenu, int aniTabMenu) {
        super(context);
        mLayout = new LinearLayout(context);
        mLayout.setOrientation(LinearLayout.VERTICAL);

        // ---- 標題選項列 ----
        gvTitle = new GridView(context);
        gvTitle.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        gvTitle.setNumColumns(titleAdapter.getCount());
        gvTitle.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
        gvTitle.setVerticalSpacing(1);
        gvTitle.setHorizontalSpacing(1);
        gvTitle.setGravity(Gravity.CENTER);
        gvTitle.setOnItemClickListener(titleClick);
        gvTitle.setAdapter(titleAdapter);
        gvTitle.setSelector(new ColorDrawable(Color.TRANSPARENT));
        this.titleAdapter = titleAdapter;

        // ---- 子選項列 ----
        gvBody = new GridView(context);
        gvBody.setLayoutParams(new LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        gvBody.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gvBody.setNumColumns(4);
        gvBody.setStretchMode(GridView.STRETCH_COLUMN_WIDTH);
        gvBody.setVerticalSpacing(10);
        gvBody.setHorizontalSpacing(10);
        gvBody.setPadding(10, 10, 10, 10);
        gvBody.setGravity(Gravity.CENTER);
        gvBody.setOnItemClickListener(bodyClick);

        mLayout.addView(gvTitle);
        mLayout.addView(gvBody);

        this.setContentView(mLayout);
        this.setWidth(LayoutParams.FILL_PARENT);
        this.setHeight(LayoutParams.WRAP_CONTENT);
        this.setBackgroundDrawable(new ColorDrawable(colorBgTabMenu));
        this.setAnimationStyle(aniTabMenu);
        // 必須可 focus,否則 menu 內的控件事件無法響應
        this.setFocusable(true);
    }

    public void SetTitleSelect(int index) {
        gvTitle.setSelection(index);
        this.titleAdapter.SetFocus(index);
    }

    public void SetBodySelect(int index, int colorSelBody) {
        int count = gvBody.getChildCount();
        for (int i = 0; i < count; i++) {
            if (i != index)
                ((LinearLayout) gvBody.getChildAt(i)).setBackgroundColor(Color.TRANSPARENT);
        }
        ((LinearLayout) gvBody.getChildAt(index)).setBackgroundColor(colorSelBody);
    }

    public void SetBodyAdapter(MenuBodyAdapter bodyAdapter) {
        gvBody.setAdapter(bodyAdapter);
    }

    /** 每個分頁的主體內容 */
    static public class MenuBodyAdapter extends BaseAdapter {
        private Context mContext;
        private int fontColor, fontSize;
        private String[] texts;
        private int[] resID;

        public MenuBodyAdapter(Context context, String[] texts, int[] resID,
                int fontSize, int fontColor) {
            this.mContext = context;
            this.fontColor = fontColor;
            this.texts = texts;
            this.fontSize = fontSize;
            this.resID = resID;
        }

        public int getCount() { return texts.length; }
        public Object getItem(int position) { return makeMenyBody(position); }
        public long getItemId(int position) { return position; }

        private LinearLayout makeMenyBody(int position) {
            LinearLayout result = new LinearLayout(this.mContext);
            result.setOrientation(LinearLayout.VERTICAL);
            result.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
            result.setPadding(10, 10, 10, 10);

            TextView text = new TextView(this.mContext);
            text.setText(texts[position]);
            text.setTextSize(fontSize);
            text.setTextColor(fontColor);
            text.setGravity(Gravity.CENTER);
            text.setPadding(5, 5, 5, 5);

            ImageView img = new ImageView(this.mContext);
            img.setBackgroundResource(resID[position]);

            result.addView(img, new LinearLayout.LayoutParams(
                    LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
            result.addView(text);
            return result;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            return makeMenyBody(position);
        }
    }

    /** 分頁標籤部分 */
    static public class MenuTitleAdapter extends BaseAdapter {
        private Context mContext;
        private int fontColor, unselcolor, selcolor;
        private TextView[] title;

        public MenuTitleAdapter(Context context, String[] titles, int fontSize,
                int fontcolor, int unselcolor, int selcolor) {
            this.mContext = context;
            this.fontColor = fontcolor;
            this.unselcolor = unselcolor;
            this.selcolor = selcolor;
            this.title = new TextView[titles.length];
            for (int i = 0; i < titles.length; i++) {
                title[i] = new TextView(mContext);
                title[i].setText(titles[i]);
                title[i].setTextSize(fontSize);
                title[i].setTextColor(fontColor);
                title[i].setGravity(Gravity.CENTER);
                title[i].setPadding(10, 10, 10, 10);
            }
        }

        public int getCount() { return title.length; }
        public Object getItem(int position) { return title[position]; }
        public long getItemId(int position) { return title[position].getId(); }

        /** 設定選中效果 */
        private void SetFocus(int index) {
            for (int i = 0; i < title.length; i++) {
                if (i != index) {
                    title[i].setBackgroundDrawable(new ColorDrawable(unselcolor));
                    title[i].setTextColor(fontColor);
                }
            }
            title[index].setBackgroundColor(0x00);
            title[index].setTextColor(selcolor);
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View v;
            if (convertView == null) {
                v = title[position];
            } else {
                v = convertView;
            }
            return v;
        }
    }
}

testTabMenu.java:資料定義與使用

package com.testTabMenu;

import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class testTabMenu extends Activity {
    TabMenu.MenuBodyAdapter[] bodyAdapter = new TabMenu.MenuBodyAdapter[3];
    TabMenu.MenuTitleAdapter titleAdapter;
    TabMenu tabMenu;
    int selTitle = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // 分頁標題
        titleAdapter = new TabMenu.MenuTitleAdapter(this,
                new String[] { "常用", "設置", "工具" },
                16, 0xFF222222, Color.LTGRAY, Color.WHITE);

        // 各分頁的內容
        bodyAdapter[0] = new TabMenu.MenuBodyAdapter(this,
                new String[] { "常用1", "常用2" },
                new int[] { R.drawable.menu_test, R.drawable.menu_bookmark },
                13, 0xFFFFFFFF);
        bodyAdapter[1] = new TabMenu.MenuBodyAdapter(this,
                new String[] { "設置1", "設置2", "設置3" },
                new int[] { R.drawable.menu_edit, R.drawable.menu_delete,
                        R.drawable.menu_fullscreen },
                13, 0xFFFFFFFF);
        bodyAdapter[2] = new TabMenu.MenuBodyAdapter(this,
                new String[] { "工具1", "工具2", "工具3", "工具4" },
                new int[] { R.drawable.menu_copy, R.drawable.menu_cut,
                        R.drawable.menu_normalmode, R.drawable.menu_quit },
                13, 0xFFFFFFFF);

        tabMenu = new TabMenu(this, new TitleClickEvent(), new BodyClickEvent(),
                titleAdapter, 0x55123456, R.style.PopupAnimation);
        tabMenu.update();
        tabMenu.SetTitleSelect(0);
        tabMenu.SetBodyAdapter(bodyAdapter[0]);
    }

    class TitleClickEvent implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            selTitle = arg2;
            tabMenu.SetTitleSelect(arg2);
            tabMenu.SetBodyAdapter(bodyAdapter[arg2]);
        }
    }

    class BodyClickEvent implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            tabMenu.SetBodySelect(arg2, Color.GRAY);
            String str = "第" + String.valueOf(selTitle) + "欄 第"
                    + String.valueOf(arg2) + "項";
            Toast.makeText(testTabMenu.this, str, 500).show();
        }
    }

    @Override
    /** 建立選單 */
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add("menu");   // 必須先建立一項,否則不會觸發 onMenuOpened
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    /** 攔截系統 Menu 按鍵 */
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (tabMenu != null) {
            if (tabMenu.isShowing()) {
                tabMenu.dismiss();
            } else {
                tabMenu.showAtLocation(findViewById(R.id.LinearLayout01),
                        Gravity.BOTTOM, 0, 0);
            }
        }
        return false;   // 回傳 true 才會顯示系統 menu
    }
}

幾個關鍵設計說明

setFocusable(true) 為什麼必要。PopupWindow 預設不搶焦點,若沒有開啟,menu 內的子控件(Button、EditText 等)就不會收到觸摸事件,點了完全沒反應。這個設定很容易漏掉,然後花半天找原因。

onCreateOptionsMenu 裡那句 menu.add("menu")看起來很多餘,但少了它,onMenuOpened 根本不會被觸發——系統認為沒有選項就不派發事件。這是攔截實體 Menu 鍵的 Necessary Evil。

選中態的雙重處理。標題列用 Adapter 內的 SetFocus() 改背景色與文字色;內容列則是呼叫 SetBodySelect() 直接遍歷子 View 改背景。兩者都搭配透明 selector,避免系統預設效果覆蓋自訂樣式。

效能上的改進空間。MenuBodyAdapter 的 getView() 每次都重新 new 一個 LinearLayout,完全沒用 convertView。選單顯示時通常要一次配置十幾個項目,這在低端機上會有可感知的延遲。正確做法是在 convertView 為 null 時才 inflate,並用 ViewHolder 模式缓存 TextView 與 ImageView 的參照。

最後談現況:Android 5.0 之後,實體 Menu 鍵在新機型上已基本消失,App 內建選單的主流做法是 BottomSheetDialogFragment 或 NavigationView。若想呈現分頁式的選單,用 TabLayout + ViewPager2 包在 BottomSheet 裡會是更標準、也更少踩坑的組合。本文這套自製 PopupWindow 的價值,在於它完整示範了「複合控件封裝」的思維——把外觀、資料、事件回呼分離成獨立可配置的類別,這份設計經驗在任何 UI 框架中都適用。

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