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

Android 自定義 View 構造函數與屬性優先級深度解析

編輯:關於 Android 程式設計

先從三個構造函數說起

寫自定義 View 時,我們通常會繼承 View 並一口氣實現三個構造函數:

 import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;

public class MyCustomView extends View {
 /** 第一個構造函數 */
 public MyCustomView(Context context) { this(context, null); }
 /** 第二個構造函數 */
 public MyCustomView(Context context, AttributeSet attrs) { this(context, attrs, 0); }
 /** 第三個構造函數 */
 public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  // TODO: 獲取自定義屬性
 }
 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); }
} 

網上關於「哪個構造函數會被調用」的說法很多,但準確的其實只有幾句:

代碼中直接 new 實例,走第一個構造函數。
XML 布局中引用,走第二個構造函數。
XML 布局中引用且標籤帶有自定義屬性,走的仍然是第二個構造函數。

結論就是:系統默認只會調用前兩個,第三個通常是我們自己串起來調用的(例如在第二個裡 this(context, attrs, 0))。而屬性的讀取,一般就放在第三個構造函數中,透過 obtainStyledAttributes 完成。

自定義屬性是怎麼生成的

做法是在 res/values/ 下新增一個資源文件(示例為 res/values/attrs_my_custom_view.xml),用 declare-styleable 聲明屬性集合:

 <resources>
 <declare-styleable name="MyCustomView">
 <attr name="custom_attr1" format="string" />
 <attr name="custom_attr2" format="string" />
 <attr name="custom_attr3" format="string" />
 <attr name="custom_attr4" format="string" />
 </declare-styleable>
 <attr name="custom_attr5" format="string" />
 </resources> 

這裡聲明了含四個屬性的 MyCustomView 集合,另外單獨聲明了一個獨立屬性 custom_attr5。所有屬性都會在 R.attr 中生成對應常量:

 public final class R {
 public static final class attr {
  public static final int custom_attr1 = 0x7f010038;
  public static final int custom_attr2 = 0x7f010039;
  public static final int custom_attr3 = 0x7f01003a;
  public static final int custom_attr4 = 0x7f01003b;
  public static final int custom_attr5 = 0x7f010000;
 }
} 

而寫在 declare-styleable 標籤內的屬性,還會額外在 R.styleable 中生成一個陣列和一串索引常量:

 public static final class styleable {
 public static final int[] MyCustomView = { 0x7f010038, 0x7f010039, 0x7f01003a, 0x7f01003b };
 public static final int MyCustomView_custom_attr1 = 0;
 public static final int MyCustomView_custom_attr2 = 1;
 public static final int MyCustomView_custom_attr3 = 2;
 public static final int MyCustomView_custom_attr4 = 3;
} 

仔細對照就會發現:R.styleable.MyCustomView 陣列裡的元素值,正好就是 R.attr.custom_attr1 到 custom_attr4;而下面那幾個常數就是它們在陣列中的下標。理解這一點,後面的取值邏輯就很順了。

在構造函數中取值

 public MyCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
  String attr1 = ta.getString(R.styleable.MyCustomView_custom_attr1);
  String attr2 = ta.getString(R.styleable.MyCustomView_custom_attr2);
  String attr3 = ta.getString(R.styleable.MyCustomView_custom_attr3);
  String attr4 = ta.getString(R.styleable.MyCustomView_custom_attr4);
  Log.e("customview", "attr1=" + attr1);
  Log.e("customview", "attr2=" + attr2);
  Log.e("customview", "attr3=" + attr3);
  Log.e("customview", "attr4=" + attr4);
  ta.recycle();
 } 

追一下源碼會發現,Context 的兩參數版本最終轉調了 Theme 的四參數版本:

 public final TypedArray obtainStyledAttributes(AttributeSet set, @StyleableRes int[] attrs) {
  return getTheme().obtainStyledAttributes(set, attrs, 0, 0);
} 

四參數版本的源碼實現:

 public TypedArray obtainStyledAttributes(AttributeSet set, @StyleableRes int[] attrs,
   @AttrRes int defStyleAttr, @StyleRes int defStyleRes) {
  final int len = attrs.length;
  final TypedArray array = TypedArray.obtain(Resources.this, len);
  final XmlBlock.Parser parser = (XmlBlock.Parser)set;
  AssetManager.applyStyle(mTheme, defStyleAttr, defStyleRes,
    parser != null ? parser.mParseState : 0, attrs, array.mData, array.mIndices);
  array.mTheme = this;
  array.mXml = parser;
  return array;
} 

這裡不糾結實現細節,把四個參數的含義講明白就夠用了:

AttributeSet set:屬性值的集合,也就是標籤上寫的那些屬性。
int[] attrs:我們自定義屬性集合在 R 類中生成的 int 陣列,裡面裝的是屬性資源 ID。
int defStyleAttr:當前 Theme 中一個指向 style 的引用。當控件沒有指定 declare-styleable 集合時,會從這裡查找布局中配置的屬性值;傳 0 表示不走這條路。
int defStyleRes:同樣指向一個 style 資源 ID,但只在 defStyleAttr 為 0,或者 Theme 裡沒有給 defStyleAttr 賦值時才會生效。

屬性賦值的優先級

同一個屬性可以在多個地方賦值,它們之間是有先後順序的。由高到低排列:

布局 XML 中直接定義 > 布局 XML 中透過 style 定義 > 所屬 Activity 的 Theme 中指定的 style 引用 > 構造函數中 defStyleRes 指定的默認值。

下面我們把 custom_attr1 到 attr4 分別放在這四個位置,用日誌驗證一下結論。

情況一:布局 XML 直接賦值

 <FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
  xmlns:custom="https://schemas.android.com/apk/res-auto"
  android:id="@+id/container"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
  <com.kevintan.eventbussample.view.MyCustomView
   android:id="@+id/id_custom_view"
   android:layout_width="400dp"
   android:layout_height="400dp"
   custom:custom_attr1="attr1_xml" />
 </FrameLayout> 

結果:attr1 拿到 attr1_xml,其餘為 null。這裡對應的是 obtainStyledAttributes 的第二個參數 attrs。

小提醒:使用自定義屬性前必須先聲明命名空間。Android Studio 推薦 xmlns:custom="https://schemas.android.com/apk/res-auto";Eclipse 下則要寫成控件所在的包名,例如 xmlns:cv="https://schemas.android.com/apk/com.kevintan.eventbussample.view"。

情況二:透過 style 賦值

 <style name="TestCustomView">
 <item name="custom_attr1">attr1_style</item>
 <item name="custom_attr2">attr2_style</item>
 </style>

布局中同時保留直接賦值並加上 style 字段後,結果是:attr1 仍然是 attr1_xml(直接賦值贏),attr2 變成 attr2_style。可見 style 的優先級僅次於直接賦值。

需要注意的是,無論是直接寫屬性還是透過 style 寫,取值時都落在第二個參數 attrs 上。

情況三:Theme 中的 defStyleAttr

官方原文:An attribute in the current theme that contains a reference to a style resource that supplies default values for the TypedArray. Can be 0 to not look for defaults.

先聲明一個 reference 型別的屬性用來承載 style 引用,寫進 attrs_my_custom_view.xml:

<attr name="MyCustomViewDefStyleAttr" format="reference"/>

然後確認 AndroidManifest.xml 中該 Activity 使用的主題:

 <activity
  android:name="com.kevintan.eventbussample.MainActivity"
  android:theme="@style/AppTheme"
  android:label="@string/app_name" >
  <intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.LAUNCHER" />
  </intent-filter>
 </activity> 

接著在 AppTheme 下把這個屬性指向一個具體的 style:

 <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
 <item name="MyCustomViewDefStyleAttr">@style/MyCustomViewDefStyleAttrImpl</item>
 </style>
 <style name="MyCustomViewDefStyleAttrImpl">
 <item name="custom_attr1">attr1_defStyleAttr</item>
 <item name="custom_attr2">attr2_defStyleAttr</item>
 <item name="custom_attr3">attr3_defStyleAttr</item>
 </style> 

代碼上要注意兩點:第二個構造函數裡要把 defStyleAttr 傳進去;取值時必須改用 getTheme().obtainStyledAttributes(...) 的三參數或四參數版本,否則第三個參數根本不會生效。

 public MyCustomView(Context context, AttributeSet attrs) {
  this(context, attrs, R.attr.MyCustomViewDefStyleAttr);
 }

 public MyCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  TypedArray ta = context.getTheme().obtainStyledAttributes(
    attrs, R.styleable.MyCustomView, defStyleAttr, 0);
  String attr1 = ta.getString(R.styleable.MyCustomView_custom_attr1);
  String attr2 = ta.getString(R.styleable.MyCustomView_custom_attr2);
  String attr3 = ta.getString(R.styleable.MyCustomView_custom_attr3);
  String attr4 = ta.getString(R.styleable.MyCustomView_custom_attr4);
  Log.e("customview", "attr1=" + attr1);
  Log.e("customview", "attr2=" + attr2);
  Log.e("customview", "attr3=" + attr3);
  Log.e("customview", "attr4=" + attr4);
  ta.recycle();
 } 

結果:attr1 = attr1_xml、attr2 = attr2_style、attr3 = attr3_defStyleAttr、attr4 = null。可見 Theme 中指定 style 引用的優先級低於 XML 直接賦值和 style 字段。

順帶一提,系統裡不少控件(例如 Button)在構造函數中就用了第三個參數,好處是切換主題時控件樣式能跟著變化。

情況四:defStyleRes

官方原文:A resource identifier of a style resource that supplies default values for the TypedArray, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults.

先定義一個 style:

 <style name="MyCustomViewDefStyleRes">
 <item name="custom_attr1">attr1_defStyleRes</item>
 <item name="custom_attr2">attr2_defStyleRes</item>
 <item name="custom_attr3">attr3_defStyleRes</item>
 <item name="custom_attr4">attr4_defStyleRes</item>
 </style>

取值時把第四個參數填上:

 TypedArray ta = context.getTheme().obtainStyledAttributes(
   attrs, R.styleable.MyCustomView, defStyleAttr, R.style.MyCustomViewDefStyleRes);

如果 defStyleAttr 仍然指向 R.attr.MyCustomViewDefStyleAttr,測試結果會讓人意外:attr4 依然是 null。原因就在前面那句話——只有 defStyleAttr 為 0,或 Theme 中沒有給 defStyleAttr 賦值時,defStyleRes 才會起作用。

所以把第二個構造函數改成傳 0:

 public MyCustomView(Context context, AttributeSet attrs) {
  // 為了驗證 defStyleRes 的作用,將 defStyleAttr 設置為 0
  this(context, attrs, 0);
 }

 public MyCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
  super(context, attrs, defStyleAttr);
  TypedArray ta = context.getTheme().obtainStyledAttributes(
    attrs, R.styleable.MyCustomView, defStyleAttr, R.style.MyCustomViewDefStyleRes);
  // ... 取值邏輯同上
  ta.recycle();
 } 

這一次結果符合預期:attr1 = attr1_xml、attr2 = attr2_style、attr3 = attr3_defStyleRes、attr4 = attr4_defStyleRes。

總結

自定義屬性的賦值優先級,記住這條鏈條即可:

布局 XML 中直接定義 > 布局 XML 中透過 style 定義 > 所屬 Activity 的 Theme 中指定的 style 引用 > 構造函數中 defStyleRes 指定的默認值。

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