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

自定義 View 實戰(二):用複合控件封裝一個可復用的 TopBar

編輯:關於 Android 程式設計

複合控件:把「一組控件」變成「一個控件」

自定義 View 的第二條路徑是創建複合控件。它的核心思路並不複雜:挑一個合適的 ViewGroup 作為父容器,把若干功能明確的子控件塞進去,再對外暴露一批可配置屬性,於是原本零散的一堆 View 就被打包成了一個語義完整、到處可複用的新控件。

這樣做的好處很直接。幾乎每款 App 的頂部都有一條標題欄,如果每個頁面都在布局文件裡手寫一遍返回鍵、標題、更多按鈕,那麼一旦設計稿改版,你得把所有頁面翻個遍。把它抽成一個 TopBar 複合控件之後,修改只發生在一處,其他頁面通過引用即可享受新樣式。



一個合格的模板必須同時具備通用性與可定製性——文字、顏色、行為都應該交給調用方決定,否則「模板」就退化成了「寫死的樣式」。下面以 TopBar 為例,走一遍完整流程。

第一步:在 attrs.xml 中聲明屬性

在 res/values 下新建 attrs.xml,用 declare-styleable 標籤集中聲明這個控件支持哪些屬性:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TopBar">
        <!-- 中間標題:文字、字號、顏色 -->
        <!-- 左按鈕:文字、背景、文字顏色 -->
        <!-- 右按鈕:文字、背景、文字顏色 -->
    </declare-styleable>
</resources>

每個屬性都要通過 format 指定類型。這裡有個容易踩的點:按鈕背景既可能是一張圖,也可能是一個純色值,因此類型要寫成 reference|color,用豎線把多種可接受的形式分隔開。

第二步:在構造方法中讀取屬性

讓 TopBar 繼承 RelativeLayout(為了簡單,直接用系統現成的容器),然後在帶 AttributeSet 的構造方法裡用 TypedArray 取值。取值的姿勢和讀系統屬性完全一樣:

// 把 attrs.xml 中 declare-styleable 聲明的所有屬性一次性收攏到 TypedArray
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);

mLeftTextColor  = ta.getColor(R.styleable.TopBar_leftTextColor, 0);
mLeftBackground = ta.getDrawable(R.styleable.TopBar_leftBackground);
mLeftText       = ta.getString(R.styleable.TopBar_leftText);

mRightTextColor = ta.getColor(R.styleable.TopBar_rightTextColor, 0);
mRightBackground= ta.getDrawable(R.styleable.TopBar_rightBackground);
mRightText      = ta.getString(R.styleable.TopBar_rightText);

mTitleTextSize  = ta.getDimension(R.styleable.TopBar_titleTextSize, 10);
mTitleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor, 0);
mTitle          = ta.getString(R.styleable.TopBar_title);

// 用完必須回收,避免資源洩露與復用時的狀態污染
ta.recycle();

R.styleable.TopBar 中的 TopBar,正是 XML 裡 name 屬性填的那個名字。取值方法也很直觀:getString()、getColor()、getDrawable()、getDimension(),每個都帶一個預設值參數作為兜底。千萬別忘記 recycle()。

第三步:把子控件組合進來

TopBar 的骨架其實就三塊:左側按鈕 mLeftButton、右側按鈕 mRightButton、中間標題 mTitleView。new 出來之後,把剛才讀到的屬性一一澆灌上去,再通過 addView() 掛進父容器:

// 賦值
mLeftButton.setTextColor(mLeftTextColor);
mLeftButton.setBackground(mLeftBackground);
mLeftButton.setText(mLeftText);

mRightButton.setTextColor(mRightTextColor);
mRightButton.setBackground(mRightBackground);
mRightButton.setText(mRightText);

mTitleView.setText(mTitle);
mTitleView.setTextColor(mTitleTextColor);
mTitleView.setTextSize(mTitleTextSize);
mTitleView.setGravity(Gravity.CENTER);

// 布局:左靠左、右靠右、標題居中
mLeftLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
mLeftLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
addView(mLeftButton, mLeftLayoutParams);

mRightLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
mRightLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
addView(mRightButton, mRightLayoutParams);

mTitleLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
mTitleLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
addView(mTitleView, mTitleLayoutParams);

第四步:用接口把行為決策權交出去

控件長什麼樣由屬性決定,而「點了之後幹什麼」不該由控件自己拍板。做法是在複合控件內部定義一個監聽接口:

public interface topbarClickListener {
    void leftClick();   // 左按鈕點擊
    void rightClick();  // 右按鈕點擊
}

接著在內部為兩個按鈕掛上點擊事件,但不寫任何業務邏輯,只把事件轉發給接口;同時對外提供一個方法讓調用方完成注入:

mLeftButton.setOnClickListener(new OnClickListener() {
    @Override public void onClick(View v) { mListener.leftClick(); }
});
mRightButton.setOnClickListener(new OnClickListener() {
    @Override public void onClick(View v) { mListener.rightClick(); }
});

// 暴露給調用方註冊回調
public void setOnTopbarClickListener(topbarClickListener mListener) {
    this.mListener = mListener;
}

調用方通常直接用匿名內部類接住,具體實現完全由自己決定:

mTopBar.setOnTopbarClickListener(new MyTopBar.topbarClickListener() {
    @Override public void leftClick()  { Toast.makeText(MainActivity.this, "left",  Toast.LENGTH_SHORT).show(); }
    @Override public void rightClick() { Toast.makeText(MainActivity.this, "right", Toast.LENGTH_SHORT).show(); }
});

除了回調,還可以再補幾個 public 方法讓外部直接操作外觀,可定製性會更上一層樓:

/**
 * 控制某個按鈕的顯示與隱藏
 * @param id    0 表示左按鈕,其他值表示右按鈕
 * @param flag  true 顯示,false 隱藏
 */
public void setButtonVisable(int id, boolean flag) {
    if (flag) {
        if (id == 0) { mLeftButton.setVisibility(View.VISIBLE); }
        else         { mRightButton.setVisibility(View.VISIBLE); }
    } else {
        if (id == 0) { mLeftButton.setVisibility(View.GONE); }
        else         { mRightButton.setVisibility(View.GONE); }
    }
}

調用起來就一行的事:

mTopBar.setButtonVisable(0, true);   // 顯示返回
mTopBar.setButtonVisable(1, false);  // 隱藏更多

第五步:引用這個 UI 模板

布局文件頂端那行大家早就見過的聲明,其實是在定義 XML 名字空間:

xmlns:android="https://schemas.android.com/apk/res/android"

因為名字被命名為 android,後面才能用 android: 前綴引用系統屬性。自定義屬性同理,只是命名空間換成 res-auto:

xmlns:custom="https://schemas.android.com/apk/res-auto"

於是標籤可以這樣寫——注意與系統控件最大的差別:標籤名必須是完整的包類路徑,屬性則走自定義名字空間:

<cmj.com.delsys.mytopbar
    android:id="@+id/topBar"
    android:layout_height="40dp"
    android:layout_width="match_parent"
    custom:title="自定義標題"
    custom:titletextcolor="#123412"
    custom:titletextsize="10sp"
    custom:leftbackground="@color/colorPrimary"
    custom:lefttext="Back"
    custom:lefttextcolor="#ffffff"
    custom:rightbackground="@color/colorPrimary"
    custom:righttext="More"
    custom:righttextcolor="#ffffff" />

如果再往前一步,把這段標籤單獨存成一個 widget_topbar.xml,別的頁面就能一行 include 搞定,模板化程度更高:

<cmj.com.delsys.mytopbar
    android:id="@+id/topBar"
    android:layout_height="40dp"
    android:layout_width="match_parent"
    custom:title="自定義標題"
    custom:titletextcolor="#123412"
    custom:titletextsize="10sp"
    custom:leftbackground="@color/colorPrimary"
    custom:lefttext="Back"
    custom:lefttextcolor="#ffffff"
    custom:rightbackground="@color/colorPrimary"
    custom:righttext="More"
    custom:righttextcolor="#ffffff"
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:custom="https://schemas.android.com/apk/res-auto" />
<include layout="@layout/widget_topbar" />

運行效果

直接運行,標題欄如預期呈現在頁面頂部:



調用 setButtonVisable() 控制左右按鈕的顯隱之後:



小結一下這條路徑的關鍵詞:attrs 聲明屬性 → TypedArray 取值並 recycle → addView 組合子控件 → 接口回調交出行為控制權 → include 完成復用。掌握了這套套路,anthony 任何重複出現的 UI 片段都能被沉澱成自己的控件庫。

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