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

Android 自定義 UI 控制項與自訂屬性的完整實作流程

編輯:關於 Android 程式設計

Android 系統內建了相當豐富的元件,但终究無法百分之百滿足每個專案的個性化需求。為了開發效率與畫面一致性,我們往往需要自行封裝 UI 控制項,把常用組合變成可重複使用的自定義 View。

自定義組合控制項的步驟大致如下:

1. 建立自訂 View
撰寫一個類別並繼承 ViewGroup 的子類,例如 RelativeLayout、LinearLayout 等。ViewGroup 是其他元件的容器,能承載各種類型的子元件。

2. 實作父類別的三個建構子
通常還要在建構子中初始化自定義的版面配置檔。

・單參數建構子:透過 new 建立物件時使用
・雙參數建構子:在版面配置檔中被引用時使用
・三參數建構子:搭配帶有 style 的版面配置時使用

3. 依需求定義 API 方法
例如對外暴露的 setter/getter,讓外部可以控制內部狀態。

4. 依需求定義自訂屬性
寫法可以參考 TextView 的屬性設計。

5. 宣告自定義命名空間

xmlns:xxx="https://schemas.android.com/apk/res/<套件包名>",其中 xxx 就是自訂的 schema 名稱。

6. 在 res/values/attrs.xml 中宣告屬性

建立屬性檔並定義,格式如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TextView">
        <!-- 自定義控件的屬性 -->
    </declare-styleable>
</resources>

7. 在版面配置中套用自訂屬性

例如:

andy:desc_off="設置自動更新已經關閉"
andy:desc_on="設置自動更新已經開啟"
andy:titles="設置自動更新"

8. 在雙參數建構子中取出屬性值

透過 AttributeSet attrs 讀出自訂屬性值,並關聯到自定義版面配置中對應的子元件。

以下用一個「設定項目」元件做完整示範。

步驟一:撰寫自定義控制項的版面配置

新增 setting_item_view.xml,由兩個 TextView、一個 CheckBox 與一條分隔線組成:

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

    <TextView
        android:id="@+id/tv_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dip"
        android:layout_marginTop="8dip"
        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="10dip"
        android:text="自動更新已經關閉"
        android:textColor="#88000000"
        android:textSize="18sp" />

    <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:layout_marginRight="10dip" />

    <View
        android:clickable="false"
        android:layout_width="match_parent"
        android:layout_height="0.2dip"
        android:layout_alignParentBottom="true"
        android:layout_marginLeft="5dip"
        android:layout_marginRight="5dip"
        android:background="#000000" />
</RelativeLayout>

步驟二:在 Activity 的版面配置中引用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:andy="https://schemas.android.com/apk/res/com.andy.mobilesafe"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.andy.mobilesafe.ui.SettingItemView
        android:id="@+id/siv_update"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        andy:desc_off="設置自動更新已經關閉"
        andy:desc_on="設置自動更新已經開啟"
        andy:titles="設置自動更新" />
</LinearLayout>

步驟三:宣告自訂屬性

在 res/values/attrs.xml 中定義:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="TextView">
        <!-- 自定義控件的屬性 -->
    </declare-styleable>
</resources>

步驟四:實作自定義控制項

繼承 ViewGroup 的子類,實作建構子與對外 API:

package com.andy.mobilesafe.ui;
import com.andy.mobilesafe.R;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;
/**
 * @author Zhang,Tianyou
 * @version 2014年11月15日 下午10:22:50
 *
 * 自定義組合控件 兩個TextView 一個checkbox 一個View
 */
public class SettingItemView extends RelativeLayout {
    private CheckBox cb_status;
    private TextView tv_title;
    private TextView tv_desc;
    private String desc_on;
    private String desc_off;
    /**
     * 初始化布局文件
     *
     * @param context
     */
    private void initView(Context context) {
        // 第二個為布局文件 root第三個參數為布局文件父類
        // 把一個布局文件 View 並加載在SettingItemView
        View.inflate(context, R.layout.setting_item_view, this);
        // View 已經加載該SettingItemView
        cb_status = (CheckBox) this.findViewById(R.id.cb_status);
        tv_desc = (TextView) this.findViewById(R.id.tv_desc);
        tv_title = (TextView) this.findViewById(R.id.title);
    }
    public SettingItemView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // 這個是可以傳遞一個樣式
        initView(context);
    }
    /**
     * 帶有兩個參數的構造方法 ,布局文件使用的時候調用
     *
     * @param context
     * @param attrs 得到屬性值
     */
    public SettingItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // 自定義布局使用調用的構造方法 attrs為配置的屬性 布局文件中使用
        initView(context);
        String titles = attrs.getAttributeValue(
                "https://schemas.android.com/apk/res/com.andy.mobilesafe", "titles");
        desc_off = attrs.getAttributeValue(
                "https://schemas.android.com/apk/res/com.andy.mobilesafe", "desc_off");
        desc_on = attrs.getAttributeValue(
                "https://schemas.android.com/apk/res/com.andy.mobilesafe", "desc_on");
        tv_title.setText(titles);
        setDesc(desc_off);
    }
    public SettingItemView(Context context) {
        super(context);
        // new 出的時候使用
        initView(context);
    }
    /**
     * 校驗組合控件是否有選中
     *
     * @return
     */
    public boolean isChecked() {
        return cb_status.isChecked();
    }
    /**
     * 設置組合控件選中
     *
     * @param checked
     */
    public void setChecked(boolean checked) {
        if (checked) {
            setDesc(desc_on);
        } else {
            setDesc(desc_off);
        }
        cb_status.setChecked(checked);
    }
    /**
     * 設置組合控件的描述信息
     *
     * @param text
     */
    public void setDesc(String text) {
        tv_desc.setText(text);
    }
}

完成後,這個 SettingItemView 就是一個可重複使用的設定列元件:標題、說明文字與勾選狀態都能透過 XML 屬性設定,也能在程式碼中動態切換,並依勾選結果自動替換描述文案。

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