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

Android 自定義組合控件:打造可複用的底部多按鈕切換列

編輯:關於 Android 程式設計

效果圖:

現在市面上大多數 App 都是這個結構:底部一排按鈕,用來切換不同的主頁面。既然每個頁面都要用,那與其複製貼上五份布局,不如基於物件導向的思路,把這一整塊封裝成一個自定義組合控件——我把它取名為 BottomLayout。

一、先規劃布局結構

最外層是一個水平的 LinearLayout,裡面放五個 weight 相同、寬度為 0dp 的 RelativeLayout。每個 RelativeLayout 裡再放兩顆檢視:一顆 Button 用 selector 顯示選中/未選中狀態,一顆 ImageView 用來顯示未讀紅點。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal">

    <RelativeLayout
        android:id="@+id/rl_home"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:clickable="true">

        <Button
            android:id="@+id/btn_home"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_centerInParent="true"
            android:background="@drawable/tab_home_selector"
            android:clickable="false" />

        <ImageView
            android:id="@+id/iv_new_home"
            android:layout_width="10dp"
            android:layout_height="10dp"
            android:layout_alignParentRight="true"
            android:layout_margin="3dp"
            android:src="@drawable/read_circle" />
    </RelativeLayout>

    <!-- 其餘 rl_encounter / rl_community / rl_message / rl_user 結構相同 -->

</LinearLayout>

二、封裝成自定義 View

package com.zyh.bottomlayout;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

/**
 * 主介面底部的按鈕切換列
 */
public class BottomLayout extends LinearLayout implements OnClickListener {

    private Context context;
    private View rl_home, rl_encounter, rl_community, rl_message, rl_user;
    private View iv_new_message, iv_new_home;
    private Button btn_home, btn_encounter, btn_community, btn_message, btn_user;

    private OnItemClickListener listener;
    private int currentPosition = 0;

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

    public BottomLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomLayout(Context context) {
        this(context, null, 0);
    }

    private void init(Context context) {
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.layout_bottom, this);

        // 五塊等分區域
        rl_home = findViewById(R.id.rl_home);
        rl_encounter = findViewById(R.id.rl_encounter);
        rl_community = findViewById(R.id.rl_community);
        rl_message = findViewById(R.id.rl_message);
        rl_user = findViewById(R.id.rl_user);

        // 五顆按鈕
        btn_home = findViewById(R.id.btn_home);
        btn_encounter = findViewById(R.id.btn_encounter);
        btn_community = findViewById(R.id.btn_community);
        btn_message = findViewById(R.id.btn_message);
        btn_user = findViewById(R.id.btn_user);

        // 未讀紅點
        iv_new_home = findViewById(R.id.iv_new_home);
        iv_new_message = findViewById(R.id.iv_new_message);
        hideHomeCircle();
        hideMessageCircle();

        changeButtonStatus(0);   // 預設在第 0 個分頁
        setListener();
    }

    public void showHomeCircle()    { iv_new_home.setVisibility(View.VISIBLE); }
    public void hideHomeCircle()    { iv_new_home.setVisibility(View.GONE); }
    public void showMessageCircle() { iv_new_message.setVisibility(View.VISIBLE); }
    public void hideMessageCircle() { iv_new_message.setVisibility(View.GONE); }

    private void setListener() {
        rl_home.setOnClickListener(this);
        rl_encounter.setOnClickListener(this);
        rl_community.setOnClickListener(this);
        rl_message.setOnClickListener(this);
        rl_user.setOnClickListener(this);
    }

    /** 對外暴露的點擊回呼 */
    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(int position);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_home:      currentPosition = 0; break;
            case R.id.rl_encounter: currentPosition = 1; break;
            case R.id.rl_community: currentPosition = 2; break;
            case R.id.rl_message:   currentPosition = 3; break;
            case R.id.rl_user:      currentPosition = 4; break;
        }
        if (listener != null) {
            listener.onItemClick(currentPosition);
        }
        changeButtonStatus(currentPosition);
    }

    /** 依目前位置切換按鈕的選中狀態 */
    private void changeButtonStatus(int position) {
        btn_home.setSelected(position == 0);
        btn_encounter.setSelected(position == 1);
        btn_community.setSelected(position == 2);
        btn_message.setSelected(position == 3);
        btn_user.setSelected(position == 4);
    }
}

這裡有幾個刻意的設計決定,值得說明:

點擊區域掛在 RelativeLayout 而不是 Button 上。Button 的 background 在切換 selector 時可能產生位移或變形,把 clickable 交給外層容器,觸控範圍更大也更穩定,同時把 Button 自己的 clickable 設為 false,避免事件被吃掉兩次。

把監聽器對外封裝。使用者只需要實作 OnItemClickListener,不必知道裡面有五顆按鈕還是七顆。

紅點顯示/隱藏獨立成方法。外部業務邏輯可以隨時控制,不必碰內部控件。

三、用 merge 消掉多餘的一層

打開布局層次檢視器,你會發現中間莫名多了一層 LinearLayout。

原因很簡單:BottomLayout 本身就繼承自 LinearLayout,而我們又寫了

LayoutInflater.from(context).inflate(R.layout.layout_bottom, this);

等於在 LinearLayout 裡再塞一個 LinearLayout。解法是把布局檔的根節點換成 merge:

<merge xmlns:android="https://schemas.android.com/apk/res/android"
    android:gravity="center"
    android:orientation="horizontal">

    <RelativeLayout
        android:id="@+id/rl_home"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:clickable="true">
        ...
    </RelativeLayout>

    <!-- 其餘四塊相同 -->

</merge>

使用 merge 之後,inflate 會把子節點直接掛到 this 上,而不是再包一層。要注意 merge 只能用在「已經有父容器」的 inflate 場景,直接對 Activity 做 setContentView 是會出錯的。

四、在主介面中使用

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <com.zyh.bottomlayout.BottomLayout
        android:id="@+id/layout_bottom"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:layout_alignParentBottom="true"
        android:background="@android:color/darker_gray" />

</RelativeLayout>
public class MainActivity extends Activity {

    private BottomLayout layout_bottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        layout_bottom = (BottomLayout) findViewById(R.id.layout_bottom);
        layout_bottom.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                Toast.makeText(MainActivity.this, "點擊了 " + position, 0).show();
            }
        });

        // 模擬延遲出現紅點
        new Handler().postDelayed(new Runnable() {
            public void run() { layout_bottom.showHomeCircle(); }
        }, 5000);
        new Handler().postDelayed(new Runnable() {
            public void run() { layout_bottom.showMessageCircle(); }
        }, 8000);
    }
}

五、可以再更好的地方

這個版本把五個分頁寫死在類別裡,如果要支援動態數量,可以改成用 SparseArray<View> 搭配 resId 陣列迴圈初始化,並把 changeButtonStatus 改為遍歷。另外,五個 RelativeLayout 的 XML 幾乎一模一樣,實務上可以用 include 搭配 layout_weight 重用,或是直接改用 LinearLayout + 自定義 drawable 背景,層級會更淺。

如果專案是新的,也值得考慮直接用 BottomNavigationView(Material Components),它內建了選中態、紅點 badge、無障礙支援與 RTL 版面,能省下不少自己刻的工夫。

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