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

Android 入門教程:初談自定義 View 與自定義屬性

編輯:關於 Android 程式設計

有些時候,我們需要在布局文件中反覆書寫大量相似代碼來定義一個又一個區塊。掌握這種最基礎的寫法固然重要,但當場景變多、需要為每一項配置不同屬性時,這種方式就顯得力不從心。系統自帶的控件也往往無法滿足需求——這時就該考慮自定義控件了。

自定義 View 的世界浩瀚無邊,值得學習的地方還有很多。它能顯著提升開發效率,掌握其基本原理與方法很有必要。接下來就從一個簡單的例子出發,一步步認識自定義 View 與自定義屬性,體會封裝的價值。之所以說是「初步」,是因為它實在太過靈活。

先看一個場景:

除了布局本身,還有個交互細節:當用戶點擊時,復選框會自動選中,紅色的說明文字變為綠色,且內容隨之改變。下面我們就一步步看看如何透過自定義 View 與自定義屬性來實現。

第一版:最直白的布局

它顯示在一個名為 SettingCenterActivity 的活動中。先用傳統方式實現布局,採用線性布局,寫下稍顯冗余的代碼:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="vertical">
    <TextView android:text="設置中心" />
    <RelativeLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent">
        <TextView
            android:id="@+id/tv_settingcenter_autoupdate_title"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_width="wrap_content"
            android:text="自動更新設置"
            android:textSize="22sp" />
        <TextView
            android:id="@+id/tv_settingcenter_autoupdate_content"
            android:layout_below="@id/tv_settingcenter_autoupdate_title"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:layout_width="wrap_content"
            android:text="自動更新已經關閉"
            android:textSize="22sp" />
        <CheckBox
            android:id="@+id/cb_settingcenter_autoupdate_checked"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content" />
        <View
            android:background="@drawable/list_devider"
            android:layout_below="@id/tv_settingcenter_autoupdate_content"
            android:layout_height="2dp"
            android:layout_width="wrap_content" />
    </RelativeLayout>
</LinearLayout>

運行後效果已實現。但問題很快浮現:若要繼續添加「黑名單攔截設置」等更多項,或想修改每一項的屬性值,就得不斷重複寫代碼,顯然浪費時間。

第二版:抽取布局並 include

第一步封裝,是把這塊布局抽取成獨立文件 item_settingcenterview.xml,再用 <include> 引入:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="vertical">
    <TextView android:text="設置中心" />
    <include layout="@layout/item_settingcenter_view" />
    <include layout="@layout/item_settingcenter_view" />
    <include layout="@layout/item_settingcenter_view" />
</LinearLayout>

看似問題都解決了,一項接著一項,十分完美。但新的難題又來了:如何修改每一項的屬性值?好像無從下手。我們會想到:如果能把整個布局當作一個 View,在主布局中像引用 TextView 那樣使用它就好了!事實上,TextView 在代碼中是一個類,正因繼承自 View 才具備了 View 的能力。那麼,我們只要自定義一個類、繼承某個容器類型的 View,是不是也就具備了 View 的屬性與功能?答案是肯定的——子類天然擁有父類的能力,甚至更強大。

第三版:自定義 View

新建一個類 SettingCenterItemView 繼承自 LinearLayout:

public class SettingCenterItemView extends LinearLayout {
    public SettingCenterItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }
    public SettingCenterItemView(Context context) {
        super(context);
        initView();
    }
    private void initView() {
        // TODO
    }
}

之所以繼承 LinearLayout,是因為它屬於容器類型的 View,可以填充其他 View(繼承 RelativeLayout 亦可)。此時它還什麼都做不了,於是接下來在 initView 中加載布局,把布局轉化為一個 View 組件並添加到容器中:

public class SettingCenterItemView extends LinearLayout {
    public SettingCenterItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }
    public SettingCenterItemView(Context context) {
        super(context);
        initView();
    }
    private void initView() {
        View view = View.inflate(getContext(), R.layout.item_settingcenter_view, null);
        addView(view);
    }
}

至此,基本的自定義 View 就完成了,可以在布局文件中引用它——注意,自定義 View 必須寫全名(含包路徑):

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:orientation="vertical">
    <TextView android:text="設置中心" />
    <com.example.ydlmobileguard.views.SettingCenterItemView
        android:layout_height="wrap_content"
        android:layout_width="match_parent" />
    <com.example.ydlmobileguard.views.SettingCenterItemView
        android:layout_height="wrap_content"
        android:layout_width="match_parent" />
</LinearLayout>

重新運行,效果與 include 一致,我們已經能像使用 LinearLayout 一樣使用自己的 View 了。但還沒結束——若就此收尾,那只不過是換了種寫法,場景需求仍未解決。接下來還要透過自定義屬性動態修改文字內容。

理解系統屬性的原理

每個布局文件都有一行命名空間聲明:xmlns:android="https://schemas.android.com/apk/res/android"。它的原理是:透過命名空間前綴找到包的信息(此處即最後一段 android),再據此定位到工程,進而找到該工程的資源信息(values 下的 attrs 屬性配置文件),最終從中讀取屬性配置。

先參考系統 attrs 文件的寫法——其中起關鍵作用的是屬性名稱(可在布局中直接引用)與屬性值的類型。對照之下,我們來定義自己的屬性。新建 attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="SettingCenterItemView">
        <!-- 添加自定義 View 需要的屬性名 -->
        <attr name="title" format="string" />
        <attr name="content" format="string" />
    </declare-styleable>
</resources>

隨後在主布局中加入自定義的命名空間前綴 xmlns:itydl="https://schemas.android.com/apk/res/com.example.ydlmobileguard",就能合法地使用這些屬性了:

<com.example.ydlmobileguard.views.SettingCenterItemView
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    itydl:content="自動更新已經關閉"
    itydl:title="自動更新設置" />
<com.example.ydlmobileguard.views.SettingCenterItemView
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    itydl:content="黑名單攔截設置已經關閉"
    itydl:title="黑名單攔截設置" />

此時運行,會發現文字並未顯示。這是因為屬性值雖然寫在了配置文件中,但組件(類)本身並不知情,需要主動讀取屬性並手動設置到界面上。

讀取並應用自定義屬性

在 SettingCenterItemView 類中完成讀取與設置:

public class SettingCenterItemView extends LinearLayout {
    private TextView tv_title;
    private TextView tv_content;
    private CheckBox cb_checkBox;
    private String[] contents;
    private View item;

    public SettingCenterItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
        initEvent();
        // 根據命名空間與屬性名讀取值
        String title = attrs.getAttributeValue(
                "https://schemas.android.com/apk/res/com.example.ydlmobileguard", "title");
        String content = attrs.getAttributeValue(
                "https://schemas.android.com/apk/res/com.example.ydlmobileguard", "content");
        tv_title.setText(title);
        // 用正則表達式截取 content:contents[0]=關閉,contents[1]=開啟
        contents = content.split("-");
    }

    private void initEvent() {
        item.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                cb_checkBox.setChecked(!cb_checkBox.isChecked());
            }
        });
        cb_checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    tv_content.setTextColor(Color.GREEN);
                    tv_content.setText(contents[1]);
                } else {
                    tv_content.setTextColor(Color.RED);
                    tv_content.setText(contents[0]);
                }
            }
        });
    }

    private void initView() {
        item = View.inflate(getContext(), R.layout.item_settingcenter_view, null);
        tv_title = (TextView) item.findViewById(R.id.tv_settingcenter_autoupdate_title);
        tv_content = (TextView) item.findViewById(R.id.tv_settingcenter_autoupdate_content);
        cb_checkBox = (CheckBox) item.findViewById(R.id.cb_settingcenter_autoupdate_checked);
        addView(item);
    }
}

此時運行,效果如下:

點擊時復選框隨之選中、文字變色變內容的「特效」也一併實現:

自定義屬性的步驟小結

  1. 定義自定義命名空間:xmlns:itheima="https://schemas.android.com/apk/res/工程的包名"。
  2. 創建 attrs.xml 文件,用 declare-styleable 聲明屬性名與類型。
  3. 在自定義組件的布局中使用這些屬性。
  4. 在自定義 View 的構造方法中,透過 attrs.getAttributeValue(命名空間, 屬性名) 讀取值,再手動設置到子控件上。

這只是一個簡單的 Demo,還有更複雜的自定義 View,將在以後繼續探討。

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