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

自製底部 Tabbar:從 RadioGroup 方案到高擴展性的自訂控件

編輯:關於 Android 程式設計

Tabbar 最早出現在 iOS,那邊用 TabBarController 就能輕鬆實作。現在的 App 大多用 Tabbar 作為功能導航,界面簡單清晰。Android 常見做法是 RadioGroup,但擴展性受限,這篇示範如何自訂一個更好用的版本。

先看實際案例——高鐵管家 App 的首頁底部就是典型的 iOS 風格 Tabbar:

方案一:RadioGroup 實現

為什麼是 RadioGroup

因為 RadioGroup 的特性正好是「只能選中一個子控件」,而 Tabbar 需要的就是單選效果,兩者天然吻合。

實作程式碼

<RadioGroup
    android:id="@+id/rgHomeMenu"
    android:layout_width="match_parent"
    android:layout_height="60dp"
    android:orientation="horizontal">

    <RadioButton
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:button="@null"
        android:checked="true"
        android:drawableTop="@drawable/icon_project_selector"
        android:gravity="center"
        android:paddingTop="8dp"
        android:paddingBottom="5dp"
        android:text="@string/project"
        android:textColor="@color/menu_txt_selector"
        android:textSize="12sp" />

    <RadioButton
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:button="@null"
        android:drawableTop="@drawable/icon_msg_selector"
        android:gravity="center"
        android:paddingTop="8dp"
        android:paddingBottom="5dp"
        android:text="@string/msg"
        android:textColor="@color/menu_txt_selector"
        android:textSize="12sp" />

    <RadioButton
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:button="@null"
        android:drawableTop="@drawable/icon_mine_selector"
        android:gravity="center"
        android:paddingTop="8dp"
        android:paddingBottom="5dp"
        android:text="@string/mine"
        android:textColor="@color/menu_txt_selector"
        android:textSize="12sp" />
</RadioGroup>

幾個要點:RadioGroup 只能以 RadioButton 作為子控件;由於 Tabbar 是「上圖下字」,必須把 android:button 設為 @null 去掉預設的圓形單選鈕,再用 android:drawableTop 放圖示;文字與顏色則分別用 text 與 textColor(搭配 selector 就能做到選中變色)。

優缺點

優點:程式碼簡潔,實現容易。

缺點:擴展性不足。每個項目都是 RadioButton,只能用這個控件本身的功能,想做客製化就束手無策。

方案二:完全自訂

需求場景

假設現在要在「消息」項目上加一個類似 iOS badge 的未讀提示:

用 RadioButton 就很難辦到,這時就得自己造輪子。整體結構是 TabGroup(容器,負責單選邏輯)加 TabItem(單項,負責狀態與子 View 同步)。

TabGroup:仿 RadioGroup 的容器

package com.snicesoft.tabbar;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

@SuppressLint("NewApi")
public class TabGroup extends LinearLayout {

    public TabGroup(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    public TabGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public TabGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TabGroup(Context context) {
        super(context);
        init();
    }

    private void init() {
        setOrientation(HORIZONTAL);
    }

    int mCheckedId = -1;
    OnTabGroupCheckedListener onTabGroupCheckedListener;

    public void setOnTabGroupCheckedListener(OnTabGroupCheckedListener onTabGroupCheckedListener) {
        this.onTabGroupCheckedListener = onTabGroupCheckedListener;
    }

    @Override
    public void addView(View child, int index, ViewGroup.LayoutParams params) {
        if (child instanceof TabItem) {
            final TabItem tab = (TabItem) child;
            if (tab.isChecked()) {
                check(tab.getId());
            }
        }
        super.addView(child, index, params);
    }

    public void check(int checkId) {
        if (mCheckedId == checkId) {
            return;
        }
        setCheckedStateForView(mCheckedId, false);
        setCheckedId(checkId);
        mCheckedId = checkId;
        if (onTabGroupCheckedListener != null) {
            onTabGroupCheckedListener.onChecked(checkId);
        }
    }

    private void setCheckedId(int id) {
        View checkedView = findViewById(id);
        if (checkedView != null && checkedView instanceof TabItem) {
            ((TabItem) checkedView).setChecked(true);
        }
    }

    private void setCheckedStateForView(int viewId, boolean checked) {
        View checkedView = findViewById(viewId);
        if (checkedView != null && checkedView instanceof TabItem) {
            ((TabItem) checkedView).setChecked(checked);
        }
    }

    public interface OnTabGroupCheckedListener {
        void onChecked(int checkedId);
    }
}

TabItem:繼承 RelativeLayout 並實作 Checkable

之所以選 RelativeLayout 而非 RadioButton,是為了讓每個項目內部能自由堆疊任意 View(圖示、文字、紅點)。既然要自己管理狀態,就必須實作 Checkable 介面。

package com.snicesoft.tabbar;

import java.util.ArrayList;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Checkable;
import android.widget.RelativeLayout;

@SuppressLint("NewApi")
public class TabItem extends RelativeLayout implements Checkable {

    private ArrayList<Checkable> chechableList = new ArrayList<Checkable>();
    private HashMap<View, StateListDrawable> stateListDrawableMap =
            new HashMap<View, StateListDrawable>();

    private static final int[] CHECKED_STATE_SET = { android.R.attr.state_checked };

    public TabItem(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init();
    }

    public TabItem(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public TabItem(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public TabItem(Context context) {
        super(context);
        init();
    }

    private void init() {
        super.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onChecked();
                if (OnClickListener != null) {
                    OnClickListener.onClick(v);
                }
            }
        });
    }

    @Override
    public void addView(View child, int index, ViewGroup.LayoutParams params) {
        super.addView(child, index, params);
        setStates(child);
    }

    /** 遞迴收集子 View 中的 Checkable 與 StateListDrawable */
    private void setStates(View child) {
        Drawable drawable = child.getBackground();
        if (drawable != null && drawable instanceof StateListDrawable) {
            stateListDrawableMap.put(child, (StateListDrawable) drawable);
        }
        child.setClickable(false);

        if (child instanceof Checkable) {
            chechableList.add((Checkable) child);
        }

        if (child instanceof ViewGroup) {
            final ViewGroup group = (ViewGroup) child;
            if (group.getChildCount() > 0) {
                for (int i = 0; i < group.getChildCount(); i++) {
                    setStates(group.getChildAt(i));
                }
            }
        }
    }

    OnClickListener OnClickListener;

    @Override
    public void setOnClickListener(OnClickListener l) {
        OnClickListener = l;
    }

    boolean isChecked = false;

    @Override
    public void setChecked(boolean checked) {
        if (isChecked == checked) {
            return;
        }
        // 把狀態同步給所有實作 Checkable 的子 View
        for (Checkable ca : chechableList) {
            ca.setChecked(checked);
        }
        if (checked) {
            for (View v : stateListDrawableMap.keySet()) {
                StateListDrawable drawable = stateListDrawableMap.get(v);
                drawable.setState(CHECKED_STATE_SET);
                v.setBackground(drawable.getCurrent());
            }
        } else {
            for (View v : stateListDrawableMap.keySet()) {
                v.setBackground(stateListDrawableMap.get(v));
            }
        }
        isChecked = checked;
    }

    private void onChecked() {
        if (getParent() instanceof TabGroup) {
            ((TabGroup) getParent()).check(getId());
        }
    }

    @Override
    public boolean isChecked() {
        return isChecked;
    }

    @Override
    public void setPressed(boolean pressed) {
        super.setPressed(pressed);
        if (!pressed) {
            setChecked(true);
        }
    }

    @Override
    public void toggle() {
        setChecked(!isChecked);
    }
}

三個設計細節值得說明

第一,所有子 View 都要設為不可點擊。RelativeLayout 中像 Button 這種帶有 pressed 狀態的控件會攔截 onClick 事件,導致點擊永遠傳不到 TabItem 本身。程式碼中 setStates() 遞迴呼叫 child.setClickable(false) 就是為了這個。

第二,setChecked 要往下同步。為了讓 TabItem 的行為與 RadioButton 一致,setChecked 中會遍歷所有實作 Checkable 的子 View 並呼叫它們的 setChecked,這樣點擊 TabItem 時狀態才能傳遞到內部元件。

第三,用 StateListDrawable 控制背景。要讓子 View 的背景能隨選中狀態變化,就得在 selector 中定義 android:state_checked,再由 setChecked 主動設定 drawable 的 state——因為子 View 的 state 不會自動跟著父容器變。

優缺點

優點:使用方式與 RadioGroup 幾乎一致,但擴展性大幅提升,項目內可以放任何 View。

缺點:layout 程式碼比 RadioGroup 多,且沒有內建的預設 checked 屬性,需要自己在 XML 中指定並於初始化時呼叫 check()。

總結

這種自訂控件本質上是在原生控件基礎上的改良,屬於比較入門的客製化手法。掌握「攔截點擊、同步狀態、控制背景」這三個原理之後,實作方式其實有很多種——例如也可以直接繼承 RadioGroup 再替換子 View 的型別,或者改用 ConstraintLayout 搭配 selector 達到同樣效果。上面的示範只是一個簡單版本,若有人有更好的改進思路,歡迎交流。

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