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

Android 複合控件實作:打造可重複使用的 TopBar 標題列

編輯:關於 Android 開發

Android 複合控件實作:打造可重複使用的 TopBar 標題列

複合控件的好處很直接:把一組常重複的 UI 與行為包成一個元件,之後任何佈局檔都能引用。下面以一個最典型的例子——頂部標題列 TopBar(左返回鍵、中間標題、右功能鍵)——走完整流程。

基本做法:繼承一個 ViewGroup(這裡選 RelativeLayout),在 構造函數中解析自訂屬性、動態建立子控件並設定版面配置。

步驟一:定義自訂屬性

在 res/values 下新增 attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TopBar">
        <attr name="title1" format="string" />
        <attr name="titleTextSize1" format="dimension" />
        <attr name="titleTextColor1" format="color" />

        <attr name="leftTextColor" format="color" />
        <attr name="leftBackground" format="reference|color" />
        <attr name="leftText" format="string" />

        <attr name="rightTextColor" format="color" />
        <attr name="rightBackground" format="reference|color" />
        <attr name="rightText" format="string" />
    </declare-styleable>
</resources>

這裡踩過一個坑值得記下:一開始我照直覺寫成 <attr name="title" format="string" />,執行時立刻出現 Attribute "title" has already been defined。原因是 title、titleTextSize、titleTextColor 在系統裡已經有既定語義,名稱被佔用了。解法有兩個:一是自己改名(我改成 title1、titleTextSize1、titleTextColor1),二是直接引用系統屬性 <attr name="android:title" />,但這時候不要再寫 format——判斷是自己宣告還是借用系統的,看有沒有 format 就知道。

步驟二:用 TypedArray 取出屬性值

必須使用帶 AttributeSet 參數的構造函數,因為屬性就是從那裡解析出來的。流程固定三步:取得 TypedArray → 逐一取值 → recycle() 回收資源(不回收,後續重建時會出錯)。

// 1. 把 attrs.xml 中定義的屬性值存進 TypedArray
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TopBar);

// 2. 取出對應的值賦給欄位
String mTitle          = ta.getString(R.styleable.TopBar_title1);
float  mTitleTextSize  = ta.getDimension(R.styleable.TopBar_titleTextSize1, 10);
int    mTitleTextColor = ta.getColor(R.styleable.TopBar_titleTextColor1, 0);

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

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

// 3. 回收資源
ta.recycle();

步驟三:動態加入子控件

用程式碼建立控制項,比全部寫死在 XML 裡更有彈性。注意版面配置參數要用 RelativeLayout.LayoutParams,並透過 addRule() 定位。

// 1. 建立控制項
mLeftButton  = new Button(context);
mRightButton = new Button(context);
mTitleView   = new TextView(context);

// 2. 套用自訂屬性
mLeftButton.setText(mLeftText);
mLeftButton.setBackground(mLeftBackground);
mLeftButton.setTextColor(mLeftTextColor);

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

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

// 3. 設定版面配置
LayoutParams mLeftParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
mLeftParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
addView(mLeftButton, mLeftParams);

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

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

步驟四:用介面回呼把點擊事件交給呼叫方

元件本身只負責「按鈕被點了」這件事,至於按下去要做什麼,應該由使用者決定。這就是介面回呼的價值。三個要點:定義介面與抽象方法 → 在需要的地方呼叫 → 對外公開一個設定方法。

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

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

呼叫方則實作介面、填入自己的邏輯:

topBar.setOnTopbarClickListener(new TopBar.topbarClickListener() {
    @Override
    public void leftClick() {
        Toast.makeText(MainActivity.this, "點擊左邊按鈕", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void rightClick() {
        Toast.makeText(MainActivity.this, "點擊右邊按鈕", Toast.LENGTH_SHORT).show();
    }
});

步驟五:引用這個 UI 模板

使用自訂控件前,要先宣告命名空間(xmlns 就是 XML Namespace)。系統的 xmlns:android="https://schemas.android.com/apk/res/android" 是同一個道理——這也解釋了為什麼每次新增 XML 檔,樣板裡總會自動帶上那一行。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:custom="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.example.geyan.textviewdemo.TopBar
        android:id="@+id/topbar"
        android:layout_width="match_parent"
        android:layout_height="40dp"

        custom:leftBackground="#ffa4c161"
        custom:leftText="Back"
        custom:leftTextColor="#FFFFFF"

        custom:rightBackground="#ffa4c161"
        custom:rightText="More"
        custom:rightTextColor="#FFFFFF"

        custom:title1="自定義標題"
        custom:titleTextColor1="#000000"
        custom:titleTextSize1="8sp">
    </com.example.geyan.textviewdemo.TopBar>

</RelativeLayout>

實務上建議不要把這段寫進 activity_main.xml,而是獨立成一個 topbar.xml,主佈局再用 <include layout="@layout/topbar" /> 引入。這樣主佈局保持乾淨,同一個標題列也能隨時搬到別的頁面重用。

歸納一下,自訂 View 與系統原生 View 最大的差異就兩點:宣告時必須寫完整的套件名稱,設定屬性時必須透過自訂的 xmlns 命名空間。

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