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

深入理解 Android 中的自定義屬性

編輯:關於 Android 程式設計

本文將透過原理解析與實例,帶大家徹底搞懂 Android 自定義屬性背後的運作機制。

一、引言

對於自定義屬性,大家應該都不陌生,通常遵循以下幾個步驟即可實現:

  • 自定義一個 CustomView(extends View)類。
  • 編寫 values/attrs.xml,在其中宣告 declare-styleable 與 attr 等標籤。
  • 在布局檔中為 CustomView 使用自定義屬性(注意命名空間)。
  • 在 CustomView 的構造方法中透過 TypedArray 取得。

然而,僅僅會背這幾步還不夠,我們更需要理解:這些步驟為什麼能奏效?styleable 到底是什麼含義、能否省略?系統已有的屬性能否直接複用?構造方法中的 AttributeSet 能否拿來取值?TypedArray 又是從哪冒不出來、為何非得用它?下面逐一解答。

二、常見的例子

先看一段最典型的程式碼化實現。

自定義屬性的聲明檔案:

 <?xml version="1.0" encoding="utf-8"?> <resources> <declare-styleable name="test"> <attr name="text" format="string" /> <attr name="testAttr" format="integer" /> </declare-styleable> </resources> 

自定義 View 類:

 package com.example.test; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.Log; import android.view.View; public class MyTextView extends View { private static final String TAG = MyTextView.class.getSimpleName(); public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.test); String text = ta.getString(R.styleable.test_testAttr); int textAttr = ta.getInteger(R.styleable.test_text, -1); Log.e(TAG, "text = " + text + " , textAttr = " + textAttr); ta.recycle(); } } 

布局檔案中使用:

 <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" xmlns:zhy="https://schemas.android.com/apk/res/com.example.test" android:layout_width="match_parent" android:layout_height="match_parent" > <com.example.test.MyTextView android:layout_width="100dp" android:layout_height="200dp" zhy:testAttr="520" zhy:text="helloworld" /> </RelativeLayout> 

運行結果為 MyTextView: text = helloworld , textAttr = 520。要留意的是,這裡 styleable 的 name 寫的是 test,並不要求一定是自定義 View 的類名。

三、AttributeSet 與 TypedArray

構造方法中的 AttributeSet 確實保存了該 View 宣告的所有屬性,而且外部可以透過它取值:

 public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); int count = attrs.getAttributeCount(); for (int i = 0; i < count; i++) { String attrName = attrs.getAttributeName(i); String attrVal = attrs.getAttributeValue(i); Log.e(TAG, "attrName = " + attrName + " , attrVal = " + attrVal); } // ==>use typedarray ... } 

輸出結果會列出 layout_width、layout_height、text、testAttr 等所有屬性,看起來 AttributeSet 無所不能。那 TypedArray 是否就可以丟掉了呢?答案是:不。

我們把布局中的屬性值改為引用類型:

 <com.example.test.MyTextView android:layout_width="@dimen/dp100" android:layout_height="@dimen/dp200" zhy:testAttr="520" zhy:text="@string/hello_world" />

此時再用 AttributeSet 取值,你會發現引用類型的屬性都變成了 @+數字的字串,根本看不懂。而最後一行透過 TypedArray 取得的卻是正確解析後的值。

這正是 TypedArray 存在的意義:當屬性值是引用類型時,若用 AttributeSet,你需要先拿到 id 再手動解析;而 TypedArray 幫我們簡化了整個過程。若真要手動解析,程式碼大致如下:

 int widthDimensionId = attrs.getAttributeResourceValue(0, -1); Log.e(TAG, "layout_width= "+getResources().getDimension(widthDimensionId)); 

四、declare-styleable

系統提供了 android:text 這樣語義明確的屬性,那我們能否直接複用呢?答案是可以。只需在 attrs.xml 中直接引用 android:text 屬性(注意複用時不需再添加 format):

 <declare-styleable name="test"> <attr name="android:text" /> <attr name="testAttr" format="integer" /> </declare-styleable> 

取值時寫成 ta.getString(R.styleable.test_android_text),布局中直接用 android:text="@string/hello_world" 即可。系統屬性的定義方式其實與我們自定義的類似,你可以在 SDK 的 platforms/android-xx/data/res/values 目錄下找到它們。

那麼 styleable 究竟能否省略?其實是可以的。若刪除 declare-styleable 標籤,attrs.xml 只剩下單純的 attr 宣告:

 <?xml version="1.0" encoding="utf-8"?> <resources> <attr name="testAttr" format="integer" /> </resources>

此時需要自己維護一個 int 陣列來對應屬性 id:

 package com.example.test; import android.content.Context; import android.content.res.TypedArray; import android.util.AttributeSet; import android.util.Log; import android.view.View; public class MyTextView extends View { private static final String TAG = MyTextView.class.getSimpleName(); private static final int[] mAttr = { android.R.attr.text, R.attr.testAttr }; private static final int ATTR_ANDROID_TEXT = 0; private static final int ATTR_TESTATTR = 1; public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); // ==>use typedarray TypedArray ta = context.obtainStyledAttributes(attrs, mAttr); String text = ta.getString(ATTR_ANDROID_TEXT); int textAttr = ta.getInteger(ATTR_TESTATTR, -1); //輸出 text = Hello world! , textAttr = 520 Log.e(TAG, "text = " + text + " , textAttr = " + textAttr); ta.recycle(); } } 

可以發現,原本的 R.styleable.test 對應到 mAttr 陣列,R.styleable.test_text 對應到下標常量 0。也就是說,declare-styleable 的作用,是讓 aapt 自動幫我們在 R.java 中生成這些 int 陣列與下標常量,省去手寫大量常量的麻煩。因此,name 通常會寫成自定義 View 的類名,只是為了直觀表達「這組屬性是供該 View 使用的」。

總結

  • attrs.xml 中的 declare-styleable 與 attr,會由 aapt 在 R.java 中生成便於使用的常量;本質上也可以只宣告所需屬性而不寫 declare-styleable。
  • 在 View 構造方法中雖可透過 AttributeSet 取值,但較為麻煩,而 TypedArray 能讓取值變得非常方便。
  • 自定義 View 時,可以直接複用系統已定義的屬性。

以上就是關於 Android 自定義屬性的完整解析,希望對大家的學習有所幫助。

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