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

Android 自訂 Tab 式選單(TabMenu)實作教學

編輯:關於 Android 程式設計

用過 UCWEB Android 版的人,大概都對它那個特殊的選單有印象:把選單做成帶分頁的 Tab 形式,能容納比 Android 傳統選單更豐富的內容(系統選單超過 6 項就會被折疊進「更多」裡)。本文在網上既有範例的基礎上做了簡化與封裝,讓它能作為一個複合控制項融入自己的 framework。

先來看執行效果:

元件結構

TabMenu 本身就是一個 PopupWindow,裡面放了兩個 GridView:第一個是分頁標籤列,位於 PopupWindow 頂部;第二個是選單本體,位於主體區域。

進出動畫的準備

為了讓 PopupWindow 有彈出與退場的動畫,先在工程的 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_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="擴展Menu----hellogv" />
</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)); // 設定 TabMenu 背景
        this.setAnimationStyle(aniTabMenu);
        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);
    }

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

        /**
         * @param context 呼叫方的上下文
         * @param texts 按鈕集合的字串陣列
         * @param resID 按鈕集合的圖示資源陣列
         * @param fontSize 按鈕字型大小
         * @param color 按鈕字型顏色
         */
        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);
        }
    }

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

        /**
         * @param context 呼叫方的上下文
         * @param titles 分頁標籤的字串陣列
         * @param fontSize 字型大小
         * @param fontcolor 字型顏色
         * @param unselcolor 未選中項的背景色
         * @param selcolor 選中項的背景色
         */
        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, // TabMenu 背景色
                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) + "欄\n\r"
                    + "第" + 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
    /** 攔截選單按鍵 */
    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 則會顯示系統選單
    }
}

幾個實作上值得注意的細節

第一是 setFocusable(true)。PopupWindow 預設不一定會取得焦點,若沒有焦點,選單內部的 GridView 點擊事件根本不會被觸發,這是很多人在這個環節卡住的原因。

第二是 onCreateOptionsMenu() 裡那個看似多餘的 menu.add("menu")。Android 的機制是「選單中沒有任何項目時不會呼叫 onMenuOpened()」,因此必須先放一個佔位項,攔截的機會才會發生,而我們在 onMenuOpened() 的最後回傳 false,系統選單自然不會顯示。

第三是 Adapter 的設計。MenuTitleAdapter 直接持有 TextView 陣列並在 getView 中回傳同一個實例,這是為了讓 SetFocus() 能直接改動每一頁標籤的外觀;代價是沒有複用 convertView,在分頁數量固定且很少的選單場景下,這個取捨是合理的。

最後提醒,本範例大量使用程式化建立 View,靈活但囉嗦;若要維護性更好的版本,可改以 XML 描述選單每一項的外觀,再用 LayoutInflater 於 getView 中 inflate。

有興趣的讀者可以動手實測這份範例,希望對你的 Android 開發有所幫助。

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