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

Android 自定義控件:組合式控件的封裝思路

編輯:關於 Android 程式設計

前面幾篇談的是「從無到有」自定義一個全新控件——繼承 View 或 ViewGroup、覆寫相關方法。這種方式難度較高,而且並不是每次需要新控件都得這樣做。很多時候,只要把系統現成的控件用佈局巧妙地組裝起來,就是一個新控件了,我稱之為自定義組合控件。

為什麼需要它

做專案時常會遇到同一段佈局被反覆複製貼上。這樣一來,XML 結構變得冗長混亂,每個控件都要在 Java 裡宣告一遍、各自掛邏輯,工作量可觀。更麻煩的是產品需求一改——加幾個、刪幾個——你就得再來一遍。

看下面這個條目:

裡面沒有任何「全新」控件,全是系統原生元件。這種佈局寫起來很快:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/rl_show_address"
    android:layout_width="match_parent"
    android:layout_height="60dip"
    android:background="@drawable/selector_blue" >

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dip"
        android:layout_marginTop="1dip"
        android:text="這是標題"
        android:textColor="#000000"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/tv_desc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_title"
        android:layout_marginLeft="6dip"
        android:layout_marginTop="1dip"
        android:text="這是描述內容"
        android:textColor="#99ff0000"
        android:textSize="14sp" />

    <CheckBox
        android:id="@+id/cb_status"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:clickable="false"
        android:focusable="false" />

    <!-- 分割線 -->
    <View
        android:layout_width="match_parent"
        android:layout_height="0.2dip"
        android:layout_alignBottom="@id/cb_status"
        android:layout_alignParentBottom="true"
        android:layout_marginTop="7dip"
        android:background="#000000" />
</RelativeLayout>

但產品如果說「這裡要放 10 個這樣的條目」,甚至之後還要隨意增刪,複製貼上就不再是好辦法了。

抽取變化點

仔細分析會發現:每個子條目的結構完全一樣,唯一在變的是標題文字,以及描述文字會隨著 CheckBox 的勾選狀態切換。既然變化點就這麼兩三個,把它們抽成屬性就好。

在 res/values 下新增 attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="combinationView">
        <attr name="title" format="string" />
        <attr name="desc_on" format="string" />
        <attr name="desc_off" format="string" />
    </declare-styleable>
</resources>

該繼承哪個類?

這裡不需要繼承 View——不是全新自定義,用不到 onMeasure 與 onDraw;也不必繼承 ViewGroup——子控件位置在 XML 裡已經定好了,用不到 onLayout。

答案是:直接繼承一個 ViewGroup 的子類。既然佈局檔的根節點是 RelativeLayout,那麼繼承 RelativeLayout 最自然,可以直接沿用它的參數與方法。反過來說,改成繼承 LinearLayout 或 FrameLayout 其實也一樣能跑,重點只是它是 ViewGroup 的子類。

CombinationView.java

package com.example.combinationview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class CombinationView extends RelativeLayout {

    // 命名空間,讀取自定義屬性時要用
    private String namespace = "https://schemas.android.com/apk/res/com.example.combinationview";

    private TextView tv_title;
    private TextView tv_desc;
    private CheckBox cb_status;

    private String title;
    private String desc_on;
    private String desc_off;

    public CombinationView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 把組合佈局渲染進來
        View view = View.inflate(context, R.layout.layout_combinationview, this);
        tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_desc = (TextView) view.findViewById(R.id.tv_desc);
        cb_status = (CheckBox) view.findViewById(R.id.cb_status);

        // 讀出自定義屬性
        title = attrs.getAttributeValue(namespace, "title");
        desc_on = attrs.getAttributeValue(namespace, "desc_on");
        desc_off = attrs.getAttributeValue(namespace, "desc_off");

        // 設定初始顯示
        if (title != null) {
            tv_title.setText(title);
        }
        if (desc_off != null) {
            tv_desc.setText(desc_off);
        }
    }

    /** 是否被勾選 */
    public boolean isChecked() {
        return cb_status.isChecked();
    }

    /** 設定勾選狀態,並同步切換描述文字 */
    public void setChecked(boolean isChecked) {
        cb_status.setChecked(isChecked);
        tv_desc.setText(isChecked ? desc_on : desc_off);
    }
}

邏輯很單純:覆寫構造方法,先 inflate 佈局,再讀屬性並套用到子控件,最後對外提供 isChecked() 與 setChecked(boolean) 兩個方法。讀者可以試著把父類改成 LinearLayout 或 FrameLayout,結果一樣可行。

在佈局中引用

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:example="https://schemas.android.com/apk/res/com.example.combinationview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.example.combinationview.CombinationView
        android:id="@+id/cv_first"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        example:desc_off="我是未被選中的描述1"
        example:desc_on="我是被選中的描述1"
        example:title="我是標題1" />

    <com.example.combinationview.CombinationView
        android:id="@+id/cv_second"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        example:desc_off="我是未被選中的描述2"
        example:desc_on="我是被選中的描述2"
        example:title="我是標題2" />

    <!-- 以此類推 -->
</LinearLayout>

程式碼精簡多了。要留意的是命名空間的宣告:

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

其中 example 是自取的別名,但必須與控件中引用屬性的前綴一致;後半段是屬性集的來源路徑,前段固定,最後一段必須是專案的套件名稱,否則會報錯。

Activity 中的邏輯

public class MainActivity extends Activity implements OnClickListener {

    private CombinationView cv_first, cv_second, cv_third, cv_fourth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        cv_first = (CombinationView) findViewById(R.id.cv_first);
        cv_second = (CombinationView) findViewById(R.id.cv_second);
        cv_third = (CombinationView) findViewById(R.id.cv_third);
        cv_fourth = (CombinationView) findViewById(R.id.cv_fourth);

        cv_first.setOnClickListener(this);
        cv_second.setOnClickListener(this);
        cv_third.setOnClickListener(this);
        cv_fourth.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        CombinationView target = null;
        switch (v.getId()) {
            case R.id.cv_first:  target = cv_first;  break;
            case R.id.cv_second: target = cv_second; break;
            case R.id.cv_third:  target = cv_third;  break;
            case R.id.cv_fourth: target = cv_fourth; break;
        }
        if (target != null) {
            target.setChecked(!target.isChecked());
        }
    }
}

總結

組合式自定義控件的概念很簡單,但非常實用。比起單純複製貼上,它不僅看起來更專業,更重要的是:把變化點收斂成屬性、把操作收斂成方法,程式的可讀性、復用性與後續維護成本都會一起改善。

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