Android自訂View建構函式詳解_Android

來源:互聯網
上載者:User

初始Custom View的建構函式

之前寫過一篇實現圓形進度條的部落格(自訂圓形進度條),通常我們在實現Custom View的時候,都會先繼承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一個Custom View執行個體的時候,會調用第一個建構函式.這個沒有任何爭議.
在xml布局檔案中調用Custom View的時候,會調用第二個建構函式.這個也沒有爭議.
在xml布局檔案中調用Custom View,並且Custom View標籤中還有自訂屬性時,這裡調用的還是第二個建構函式.
也就是說,系統預設只會調用Custom View的前兩個建構函式,至於第三個建構函式的調用,通常是我們自己在建構函式中主動調用的(例如,在第二個建構函式中調用第三個建構函式).

至於自訂屬性的擷取,通常是在建構函式中通過obtainStyledAttributes函數實現的.這裡先介紹一下如何產生Custom View的自訂屬性.

產生Custom View的自訂屬性

Custom View添加自訂屬性主要是通過declare-styleable標籤為其配置自訂屬性,具體做法是: 在res/values/目錄下增加一個resources xml檔案,樣本如下(res/values/attrs_my_custom_view.xml):

<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>

在上述xml檔案中,我們聲明了一個自訂屬性集MyCustomView,其中包含了custom_attr1,custom_att2,custom_attr3,custom_attr4四個屬性.同時,我們還聲明了一個獨立的屬性custom_attr5.

所有resources檔案中聲明的屬性都會在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; }}

但是聲明在標籤中的屬性,系統還會在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~R.attr.custom_attr4的值.而下面的MyCustomView_custom_attr1~MyCustomView_custom_attr4正好就是其對應的索引.

知道了這些之後,我們就可以來學習一下,如何在Custom View的建構函式中擷取自訂屬性的值了.

在Custom View的建構函式中擷取自訂屬性

在第三個建構函式中擷取自訂屬性的代碼如下:

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.obtainStyledAttributes這個函數,相信這個函數大家自訂View的時候都用的很熟練了.我們來看一下這個函數的源碼實現:

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

通過對源碼的追蹤,我們發現context的兩個參數的obtainStyledAttributes方法最終是調用了Theme的4個參數的obtainStyledAttributes方法.我們來看一下這個函數的源碼實現:

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); // XXX note that for now we only work with compiled XML files. // To support generic XML files we will need to manually parse // out the attributes from the XML file (applying type information // contained in the resources and such). 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; if (false) {  int[] data = array.mData;  System.out.println("Attributes:");  String s = " Attrs:";  int i;  for (i=0; i<set.getAttributeCount(); i++) {   s = s + " " + set.getAttributeName(i);   int id = set.getAttributeNameResource(i);   if (id != 0) {    s = s + "(0x" + Integer.toHexString(id) + ")";   }   s = s + "=" + set.getAttributeValue(i);  }  System.out.println(s);  s = " Found:";  TypedValue value = new TypedValue();  for (i=0; i<attrs.length; i++) {   int d = i*AssetManager.STYLE_NUM_ENTRIES;   value.type = data[d+AssetManager.STYLE_TYPE];   value.data = data[d+AssetManager.STYLE_DATA];   value.assetCookie = data[d+AssetManager.STYLE_ASSET_COOKIE];   value.resourceId = data[d+AssetManager.STYLE_RESOURCE_ID];   s = s + " 0x" + Integer.toHexString(attrs[i])    + "=" + value;  }  System.out.println(s); } return array;}

這裡就不做過多的源碼講解,而是把這四個參數的含義解釋給大家:

AttributeSet set: 屬性值的集合.

int[] attrs: 我們自訂屬性集合在R類中產生的int型數組.這個數組中包含了自訂屬性的資源ID.
int defStyleAttr: 這是當前Theme中的包含的一個指向style的引用.當我們沒有給自訂View設定declare-styleable資源集合時,預設從這個集合裡面尋找布局檔案中配置屬性值.傳入0表示不像該defStyleAttr中尋找預設值.
int defStyleRes: 這個也是一個指向Style的資源ID,但是僅在defStyleAttr為0或者defStyleAttr不為0但Theme中沒有為defStyleAttr屬性賦值時起作用.

由於一個屬性可以在很多地方對其進行賦值,包括: XML布局檔案中、decalare-styleable、theme中等,它們之間是有優先順序次序的,按照優先順序從高到低排序如下:

屬性賦值優先順序次序表:

在布局xml中直接定義 > 在布局xml中通過style定義 > 自訂View所在的Activity的Theme中指定style引用 > 建構函式中defStyleRes指定的預設值

為了讓大家有更清楚更直觀的瞭解,再接下來設定自訂屬性的章節中,我將對custom_attr1~4這4個屬性分別在上述四個地方進行定義,然後在Custom View的建構函式中擷取它的值,從而看一下,優先順序順序是否和我們預期的一樣.

設定自訂屬性值

以下的第幾個參數均是針對Resources.Theme類的obtainStyledAttributes四參數構造方法來說明的.

第二個參數——在布局xml檔案中為屬性賦值

在設定自訂屬性之前,我們首先要在主Activity的布局檔案中調用我們的Custom View,並且為其設定特定的屬性.

主布局檔案內容如下:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://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"  style="@style/TestCustomView"/></FrameLayout>

樣本結果:

05-28 17:19:56.542 23575-23575/? E/customview: attr1=attr1_xml
05-28 17:19:56.542 23575-23575/? E/customview: attr2=null
05-28 17:19:56.542 23575-23575/? E/customview: attr3=null
05-28 17:19:56.542 23575-23575/? E/customview: attr4=null

注意:

在給自訂屬性賦值時,首先需要增加自訂屬性的命名空間,例如: xmlns:custom=”http://schemas.Android.com/apk/res-auto”,Android Studio推薦使用res-auto,在Eclipse中需要使用Custom View所在的包名: xmlns:cv=”http://schemas.android.com/apk/com.kevintan.eventbussample.view”
這裡,在布局檔案中我們為custom_attr1賦值為: attr1_xml.自訂View中擷取該屬性值對應了getTheme().obtainStyledAttributes方法中的第二個參數@StyleableRes int[] attrs

第二個參數——在style中為屬性賦值

其次,自訂屬性還可以在Style中進行賦值.

首先,我們在xml布局檔案中還為MyCustomView增加一個自訂的style,style代碼如下:

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

然後,我們修改布局檔案,增加style欄位:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:custom="http://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"  style="@style/TestCustomView"/></FrameLayout>

樣本結果:

05-28 17:19:56.542 23575-23575/? E/customview: attr1=attr1_xml
05-28 17:19:56.542 23575-23575/? E/customview: attr2=attr2_style
05-28 17:19:56.542 23575-23575/? E/customview: attr3=null
05-28 17:19:56.542 23575-23575/? E/customview: attr4=null

這裡我們再次對custom_attr1屬性進行了賦值,同時我們對custom_attr2也進行了賦值.

小提示:

聰明的同學肯定都猜到我這樣賦值的作用了,但是還是要簡述一下:
對於custom_attr1,我們在xml布局檔案、style、defStyle和theme中均進行賦值,那最終得到的結果必然能證實誰的優先順序最高.
對於custom_attr2,我們在style、defStyle和theme中進行賦值,通過得到的結果我們能知道誰的優先順序第二高.
對於custom_attr3和custom_attr4的賦值情況我就不多解釋了,我相信大家都懂得!!
同時,還需要大家注意的是,只要是layout布局檔案中,無論是通過namespace直接為屬性賦值,還是通過style為屬性賦值,在建構函式擷取時都對應了getTheme().obtainStyledAttributes方法中的第二個參數@StyleableRes int[] attrs

第三個參數defStyleAttr

這個參數的意思是:

原文: An attribute in the current theme that contains areference to a style resource that supplies defaults values for the TypedArray. Can be 0 to not look for defaults.
翻譯: 這是當前Theme中的包含的一個指向style的引用.當我們沒有給自訂View設定declare-styleable資源集合時,預設從這個集合裡面尋找布局檔案中配置屬性值.傳入0表示不向該defStyleAttr中尋找預設值.
為了測試該參數的作用和優先順序,我們需要進行如下操作.

首先, 我們先聲明一個refrence格式的屬性, 用於表示style的引用.聲明在之前的res/values/attrs_my_custom_view.xml檔案裡即可:

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

然後,需要到AndroidManifest.xml中查看包含該自訂View的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>

最後,在style.xml中的AppTheme主題下增加MyCustomViewDefStyleAttr的引用實現.

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar"> <!-- Customize your theme here. --> <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>

代碼驗證,記住如果要使用obtainStyledAttributes方法的第三個參數, 就需要在第三個建構函式中顯示的調用getTheme()的obtainStyledAttributes方法.

public MyCustomView(Context context, AttributeSet attrs) { // 為defStyleAttr進行賦值 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();}

代碼中,有兩點需要大家注意:

我在第二個構造參數中已經對defStyleAttr進行了賦值,第三個構造參數直接使用傳入參數即可.
第三個構造參數中,我使用了getTheme()的obtainStyledAttributes方法來代替context的2個參數的obtainStyledAttributes構造方法.
樣本結果:

05-28 17:19:56.542 23575-23575/? E/customview: attr1=attr1_xml
05-28 17:19:56.542 23575-23575/? E/customview: attr2=attr2_style
05-28 17:19:56.542 23575-23575/? E/customview: attr3=attr3_defStyleAttr
05-28 17:19:56.542 23575-23575/? E/customview: attr4=null

從結果可以看出,在主題中指定style引用的優先順序是低於在xml中直接賦值和使用style欄位的.

同時,我們還需要瞭解一點:
在Android系統中的控制項,很多都在構造參數中使用了第三個參數,例如Button.這樣做的好處是: 當我們切換不同的主題時,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的資源ID,但是僅在defStyleAttr為0或者defStyleAttr不為0但Theme中沒有為defStyleAttr屬性賦值時起作用.
通過翻譯,我們可以明確兩點:

1.defStyleRes: 指向一個style引用.
2.defStyleRes的優先順序低於defStyleAttr.
為了驗證,我們先在theme.xml檔案中定義一個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>

然後,我們在自訂View的第三個建構函式中的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); // 為defStyleRes進行賦值 TypedArray ta = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyleAttr, R.style.MyCustomViewDefStyleRes); 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();}

測試結果:

05-28 17:44:09.282 3137-3137/? E/customview: attr1=attr1_xml
05-28 17:44:09.282 3137-3137/? E/customview: attr2=attr2_style
05-28 17:44:09.282 3137-3137/? E/customview: attr3=attr3_defStyleAttr
05-28 17:44:09.282 3137-3137/? E/customview: attr4=null

重點:
如果大家認真的看實驗結果,肯定會被上面的結果感到奇怪,明明指定了defStyleRes,為什麼attr4的值還是null?
是因為之前講過defStyleRes的使用優先順序:只有當defStyleAttr為0或者當前Theme中沒有給defStyleAttr屬性賦值時才起作用.

所以,這裡我們需要修改建構函式,將defStyleAttr設定為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); 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();}

最終結果:

05-28 17:49:03.707 5772-5772/? E/customview: attr1=attr1_xml
05-28 17:49:03.707 5772-5772/? E/customview: attr2=attr2_style
05-28 17:49:03.707 5772-5772/? E/customview: attr3=attr3_defStyleRes
05-28 17:49:03.707 5772-5772/? E/customview: attr4=attr4_defStyleRes

後記

在文章結尾, 我們再次總結一下自訂屬性的屬性賦值優先順序:

在布局xml中直接定義 > 在布局xml中通過style定義 > 自訂View所在的Activity的Theme中指定style引用 > 建構函式中defStyleRes指定的預設值.

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.