編輯:關於 Android 程式設計
本文將透過原理解析與實例,帶大家徹底搞懂 Android 自定義屬性背後的運作機制。
對於自定義屬性,大家應該都不陌生,通常遵循以下幾個步驟即可實現:
然而,僅僅會背這幾步還不夠,我們更需要理解:這些步驟為什麼能奏效?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 確實保存了該 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));
系統提供了 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 使用的」。
以上就是關於 Android 自定義屬性的完整解析,希望對大家的學習有所幫助。
Android 如何取得 SHA1 憑證指紋?keytool 指令一次搞定
為什麼需要 SHA1 在 Android 開發中,SHA1 憑證指紋是很常被要求的一項資訊。最典型的例子就是接入高德地圖——沒有它,Key 就申請不下來。 過去用 Ecl
用Java操作Ant壓縮解壓檔案並批量打包Android應用
實現zip/tar的壓縮與解壓Java其實本身就提供了對zip等壓縮格式的支援,那為什麼這裡要用到ant呢?主要有兩個原因:1. Java提供的類對包含中文字元的路徑、檔
主流 Android 熱修復技術比較:超級補丁、Tinker 與 HotFix
熱修復的核心問題 Android 熱修復的目標,是在不重新發版的情況下修復線上問題。常見方案包括類加載、DEX 合併與 Native 方法替換。不同方案在生效速度、相容性
Android SpannableString 詳解:讓文字擁有變色、點擊與多樣樣式
引言 在 App 開發過程中,經常需要對一段文字做細緻的加工,例如替其中某幾個字設定不同的前景色,或為局部文字掛上點擊事件。要達成這類需求,SpannableString