Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

自定義 View 加屬性的兩種寫法:Arena 級對比與選擇建議

編輯:Android 開發實例

Android SDK 提供的基礎元件再多,也總有畫不出來的需求,於是我們繼承、改寫、擴充。而擴充的第一步往往是:怎麼讓這個自訂 View 在 XML 裡「吃參數」?

常見的做法有兩種,寫起來差別不大,但規範性與能力差距明顯。以下用同一個需求——一個「文字 + 輸入框」的組合元件——分別實作。

寫法一:直接從 AttributeSet 取值

package com.terry.attrs;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EditTextExt1 extends LinearLayout {

    private String Text = "";

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

    public EditTextExt1(Context context, AttributeSet attrs) {
        super(context, attrs);

        TextView tv = new TextView(context);
        EditText et = new EditText(context);

        int resouceId = attrs.getAttributeResourceValue(null, "Text", 0);
        if (resouceId > 0) {
            Text = context.getResources().getText(resouceId).toString();
        } else {
            Text = "";
        }
        tv.setText(Text);

        addView(tv);
        addView(et, new LinearLayout.LayoutParams(
                LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        this.setGravity(LinearLayout.VERTICAL);
    }
}

使用時直接在 XML 寫上自屬性即可,不必額外宣告任何資源檔:

<com.terry.attrs.EditTextExt1
    android:id="@+id/ss3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    Text="@string/app_name" />

優點很直白:零配置、程式碼短、直觀易懂。缺點也很致命——屬性名稱寫在字串裡,編譯器完全不檢查,打錯字只會靜默失效。

寫法二:declare-styleable + TypedArray

先在 res/values/attrs.xml 宣告:

<?xml version="1.0" encoding="UTF-8"?>
<resources>
    <declare-styleable name="EditTextExt">
        <attr name="Text" format="reference|string"></attr>
        <attr name="Oriental">
            <enum name="Horizontal" value="1"></enum>
            <enum name="Vertical" value="0"></enum>
        </attr>
    </declare-styleable>
</resources>

Java 端則用 obtainStyledAttributes() 取出型別化陣列:

package com.terry.attrs;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

public class EditTextExt extends LinearLayout {

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

    public EditTextExt(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typeArray = context.obtainStyledAttributes(
                attrs, R.styleable.EditTextExt);

        TextView tv = new TextView(context);
        EditText et = new EditText(context);

        int N = typeArray.getIndexCount();
        for (int i = 0; i < N; i++) {
            int attr = typeArray.getIndex(i);
            switch (attr) {
                case R.styleable.EditTextExt_Oriental:
                    int orientation = typeArray.getInt(
                            R.styleable.EditTextExt_Oriental, 0);
                    this.setOrientation(orientation == 1
                            ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL);
                    break;
                case R.styleable.EditTextExt_Text:
                    int resouceId = typeArray.getResourceId(
                            R.styleable.EditTextExt_Text, 0);
                    tv.setText(resouceId > 0
                            ? typeArray.getResources().getText(resouceId)
                            : typeArray.getString(R.styleable.EditTextExt_Text));
                    break;
            }
        }

        addView(tv);
        addView(et);
        typeArray.recycle();
    }
}

命名規則是關鍵

ADT 會依 declare-styleable 的名稱,為其中每個 attr 自動產生一組常數,格式是「styleable 名稱 + 底線 + 屬性名稱」。所以 EditTextExt 下的 Text 對應 R.styleable.EditTextExt_Text。這一點可以直接對照 R.java 驗證:

public static final class styleable {
    public static final int[] EditTextExt = {
            0x7f010000, 0x7f010001
    };
    public static final int EditTextExt_Oriental = 1;
    public static final int EditTextExt_Text = 0;
};

在 XML 中使用

先宣告自有的命名空間,指向應用程式的 package 名稱:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:terry="https://schemas.android.com/apk/res/com.terry.attrs"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <com.terry.attrs.EditTextExt
        android:id="@+id/ss"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        terry:Text="fdsafda"
        terry:Oriental="Vertical">
    </com.terry.attrs.EditTextExt>

    <com.terry.attrs.EditTextExt1
        android:id="@+id/ss3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        Text="@string/app_name" />
</LinearLayout>

寫法二的使用方式與系統內建元件完全一致——宣告命名空間,然後用 terry:Text 指定。這本身就是一種可讀性優勢。

五點關鍵差異

  • 編譯期檢查:寫法二的屬性名稱由 R.java 產生常數,打錯字直接編譯失敗;寫法一的字串寫錯不會報錯,只會安靜地什麼都不發生。
  • 風格統一:寫法二與 Android 官方屬性的宣告方式一致,團隊協作時規則清楚。
  • 型別驗證:透過 format 宣告型別(reference、integer、string、color…),可限制開發者只能傳合法值,寫法一做不到。
  • 提供有限選項:用 <enum> 或 <flag> 能把屬性變成下拉選單,Android Studio 甚至會自動提示,寫法一只能吃字串。
  • 取值彈性:寫法一的屬性幾乎必須是資源引用;寫法二同時支援資源引用與直接輸入。

那到底該選哪個

結論很清楚:只要這個自定義 View 會被團隊使用、會長期維護、或需要型別約束,就用寫法二。寫法一適合的是拋棄型原型、內部一次性腳本,或你確信屬性永遠不會拼錯的極簡場景。

個人建議把「一個自定義 View 對應一個 declare-styleable」當成預設習慣,這也是多數成熟開源元件庫的做法。

原文出處:https://www.cnblogs.com/TerryBlog/archive/2010/11/03/1868431.html

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