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

Android 自定義控件實戰:打造可複用的標題欄組合控件(自定義屬性 + 接口回調)

編輯:關於 Android 程式設計

前面我們聊過其中一種自定義 View 的做法(音頻條)。那篇的建議今天仍然有效:一次只學會一種技術,看完自己動手做一遍,再試著加點功能擴展,比一次吞五篇有用得多。

今天要學的是另一條路線——建立可重複使用的組合控件,並以 App 裡最常見的「統一風格標題欄」作為演練題目。

一、兩個名詞先定義清楚

什麼是「可重複使用」?同一套程式碼能在 App 多個頁面共用。好處很直接:少寫重複的 XML、改一次樣式全站生效、風格不會各頁各異。標題欄正是最典型的例子。

什麼是「組合控件」?把多個現成控件組合在一起,彼此協作完成某個特定功能。這裡我們要組合的就是「左邊返回 + 中間標題 + 右邊動作」這樣的結構。

二、選擇容器並建立類別

組合控件需要一個容器來裝子控件,可用的 Layout 很多,這裡選 RelativeLayout,因為標題欄的三段式對齊用相對定位最好寫。

先定義 CompositeViews 繼承 RelativeLayout,並把三個建構子都補齊(自定義 View 在 Java 與 XML 中被建立時,走的建構子不同,缺一個就會在預覽或執行時出問題):

public class CompositeViews extends RelativeLayout {

    public CompositeViews(Context context) {
        this(context, null);
    }

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

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

三、加入三個子 TextView

接著宣告三個 TextView,分別負責「返回」、「標題」、「搜尋」,並用 LayoutParams 決定各自在容器中的對齊方式:

public class CompositeViews extends RelativeLayout {

    private TextView mLeftText;
    private TextView mRightText;
    private TextView textTitle;

    private LayoutParams leftLayoutParams;
    private LayoutParams rightLayoutParams;
    private LayoutParams titleLayoutParams;

    public CompositeViews(Context context) {
        this(context, null);
    }

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

    public CompositeViews(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }
}

initView() 負責初始化與定位:

private void initView(Context context) {
    mLeftText  = new TextView(context);
    mRightText = new TextView(context);
    textTitle  = new TextView(context);

    /* 左按鈕:靠左對齊 */
    leftLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    leftLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
    mLeftText.setText("返回");
    mLeftText.setTextSize(22);

    /* 右按鈕:靠右對齊 */
    rightLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    rightLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
    mRightText.setText("搜尋");
    mRightText.setTextSize(22);

    /* 標題:置中 */
    titleLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    titleLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
    textTitle.setText("這是一個標題");
    textTitle.setTextSize(22);
}

把自定義 View 放進佈局檔並在 Activity 載入:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
    android:background="#999999"
    android:orientation="vertical">

    <com.sanhuimusic.mycustomview.view.CompositeViews
        android:id="@+id/topBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

MainActivity

public class MainActivity extends AppCompatActivity {

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

執行起來確實有畫面了:

但問題也很明顯:文字、字級、顏色全寫死在 Java 裡。既然目標是「可複用」,寫死就等於白做——換個頁面標題不同、配色不同,難道要改原始碼?所以下一步就是自定義屬性。

四、定義自定義屬性

在 res/values 下新增 attrs.xml(Eclipse 專案通常已內建,Android Studio 需自行建立):

<?xml version="1.0" encoding="utf-8"?>
<resources>
</resources>

用 <declare-styleable> 宣告一組屬性,它的 name 就是之後在程式碼中查找這組屬性的索引:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CompositeViews">
        <attr name="titleText"       format="string" />
        <attr name="titleTextSize"   format="dimension" />
        <attr name="titleColor"      format="color" />
        <attr name="titleBackground" format="color|reference" />

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

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

以 <attr name="titleText" format="string" /> 為例:name 是屬性名稱,format 宣告型別。常見的 format 有 string、dimension、color、reference、boolean、integer 等;color|reference 表示「可以是顏色值,也可以是資源參照」,這對背景特別有用,因為背景常是圖片或 shape 資源。

五、在 XML 中使用自定義屬性

使用前必須先宣告自定義命名空間,寫在根節點上:

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

custom 是命名空間別名,可任意命名,之後引用自定義屬性都要以它開頭:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="wrap_content"
    android:background="#999999"
    android:orientation="vertical">

    <com.sanhuimusic.mycustomview.view.CompositeViews
        android:id="@+id/topBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        custom:titleText="@string/titleText"
        custom:titleColor="#000000"
        custom:titleTextSize="@dimen/titleTextSize"
        custom:titleBackground="#999999"
        custom:leftText="@string/leftText"
        custom:leftTextColor="#FFFFFF"
        custom:leftBackground="#666666"
        custom:leftTextSize="@dimen/leftTextSize"
        custom:rightText="@string/rightText"
        custom:rightTextColor="#FFFFFF"
        custom:rightBackground="#666666"
        custom:rightTextSize="@dimen/rightTextSize" />
</LinearLayout>

六、在程式碼中讀取自定義屬性

XML 寫好的屬性要生效,得靠 TypedArray 讀出來。它被封裝了各種型別的 getter,用法如下:

private void initView(Context context, AttributeSet attrs) {
    mLeftText  = new TextView(context);
    mRightText = new TextView(context);
    textTitle  = new TextView(context);

    /** 獲取自定義屬性 */
    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.CompositeViews);

    String  titleText       = typedArray.getString(R.styleable.CompositeViews_titleText);
    float   titleTextSize   = typedArray.getDimension(R.styleable.CompositeViews_titleTextSize, 16);
    int     titleColor      = typedArray.getColor(R.styleable.CompositeViews_titleColor, 0);
    Drawable titleBackground = typedArray.getDrawable(R.styleable.CompositeViews_titleBackground);

    String  leftText       = typedArray.getString(R.styleable.CompositeViews_leftText);
    int     leftTextColor  = typedArray.getColor(R.styleable.CompositeViews_leftTextColor, 0);
    float   leftTextSize   = typedArray.getDimension(R.styleable.CompositeViews_leftTextSize, 16);
    Drawable leftBackground = typedArray.getDrawable(R.styleable.CompositeViews_leftBackground);

    String  rightText       = typedArray.getString(R.styleable.CompositeViews_rightText);
    int     rightTextColor  = typedArray.getColor(R.styleable.CompositeViews_rightTextColor, 0);
    float   rightTextSize   = typedArray.getDimension(R.styleable.CompositeViews_rightTextSize, 16);
    Drawable rightBackground = typedArray.getDrawable(R.styleable.CompositeViews_rightBackground);

    typedArray.recycle();   // 用完記得回收

    /* 左按鈕 */
    leftLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    leftLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_LEFT, TRUE);
    mLeftText.setText(leftText);
    mLeftText.setTextColor(leftTextColor);
    mLeftText.setTextSize(leftTextSize);
    mLeftText.setBackground(leftBackground);
    addView(mLeftText, leftLayoutParams);

    /* 右按鈕 */
    rightLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    rightLayoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, TRUE);
    mRightText.setText(rightText);
    mRightText.setTextColor(rightTextColor);
    mRightText.setTextSize(rightTextSize);
    mRightText.setBackground(rightBackground);
    addView(mRightText, rightLayoutParams);

    /* 中間標題 */
    titleLayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    titleLayoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, TRUE);
    textTitle.setText(titleText);
    textTitle.setTextSize(titleTextSize);
    textTitle.setTextColor(titleColor);
    textTitle.setBackground(titleBackground);
    addView(textTitle, titleLayoutParams);
}

對應的建構子也要把 attrs 往下一層傳:

public CompositeViews(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    initView(context, attrs);
}

流程是:透過 context 把屬性集讀進 TypedArray → 用它的 getter 逐項取值(第二個參數是XML沒給值時的預設)→ 套到各子控件上 → recycle() 回收。至此標題欄已完全可配置,任何頁面只要放進這個 View 並設定屬性即可,不必再改 Java 程式碼。

七、用接口回調把「行為」交給呼叫者

還缺一塊:使用者點「返回」或「搜尋」時要做什麼?標題欄自己不知道,也不該知道。做法是回調——控件只負責觸發事件,功能由呼叫頁面實作。

先定義接口:

public interface TopBarClickListener {
    void leftClickListener();
    void rightClickListener();
}

在控件內部綁定點擊,但只負責轉發:

private void setListener() {
    mLeftText.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mTopBarClickListener.leftClickListener();
        }
    });

    mRightText.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mTopBarClickListener.rightClickListener();
        }
    });
}

把接口暴露給外部:

public void setOnTopBarClickListener(TopBarClickListener topBarClickListener) {
    mTopBarClickListener = topBarClickListener;
}

最後,誰使用誰實作。以 MainActivity 為例,先跳個 Toast 就好:

public class MainActivity extends AppCompatActivity {

    private CompositeViews topBar;

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

        topBar = (CompositeViews) findViewById(R.id.topBar);
        topBar.setOnTopBarClickListener(new CompositeViews.TopBarClickListener() {
            @Override
            public void leftClickListener() {
                ToastUtil.makeText(MainActivity.this, "您點擊了返回鍵", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void rightClickListener() {
                ToastUtil.makeText(MainActivity.this, "您點擊了搜尋鍵", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

執行結果:

小結

這篇走完了一條完整的自定義控件路徑:繼承現成容器 → 組合子 View → 自定義屬性讓外觀可配置 → 接口回調讓行為可注入。四步湊齊,控件才真正具備複用價值:同一份程式碼,換屬性就換風格,換監聽就換行為。

建議動手做一兩個變體練習,例如加上中間的返回箭頭圖示、或讓標題支援副標題,你會對 TypedArray 與回調的寫法更熟悉。

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