編輯:關於 Android 程式設計
近來在研究 Android 自定義控件的屬性,把 TypedArray 和 attrs 這套機制徹底摸了一遍,收穫頗多。本文就把整個流程梳理清楚,後續還會有實戰應用的續篇。
<!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--> <resources> <attr name="titleText" format="string"> <attr name="titleTextColor" format="color"> <attr name="titleTextSize" format="dimension"> <declare-styleable name="AuthCodeView"> <attr name="titleText"> <attr name="titleTextColor"> <attr name="titleTextSize"> </attr></attr></attr></declare-styleable> </attr></attr></attr></resources>
這段代碼定義了三個屬性。首先用 attr 標籤聲明每個屬性的名字和格式;接著用 declare-styleable 組把這些屬性歸集成一個名為 AuthCodeView 的樣式集合,這個名字稍後會在 class 中用到。
對比系統自帶控件的屬性用法,其實大同小異。先看兩張圖,大半問題就明白了。
a、自定義屬性的名字引用

b、仔細對照圖中的說明,以及 a、b 兩圖的差異,你就能明白屬性名該怎麼起、又該怎麼引用。

怕圖片看不清,附上部分 XML 代碼:
<linearlayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="https://schemas.android.com/tools" xmlns:authcodeview="https://schemas.android.com/apk/res/com.example.authcodeview" android:id="@+id/LinearLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content"> <com.example.authcodeview.view.authcodeview android:id="@+id/AuthCodeView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" authcodeview:titletext="3712" authcodeview:titletextcolor="#00ffff" authcodeview:titletextsize="40sp"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="點擊驗證碼,換一張"> </textview></com.example.authcodeview.view.authcodeview></linearlayout> <linearlayout android:layout_width="match_parent" android:layout_height="wrap_content"> <textview android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="輸入驗證碼"> <edittext android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputtype="number"> <requestfocus> </requestfocus></edittext> </textview></linearlayout><button android:id="@+id/button1" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="驗證"></button></linearlayout>
請重點留意頭部 layout 中的 xmlns:android="https://schemas.android.com/apk/res/android",它是引用系統屬性的關鍵。而 xmlns:authcodeview="https://schemas.android.com/apk/res/com.example.authcodeview" 則是引用我們自己定義的屬性。
規律很簡單:
xmlns:+名稱 ="https://schemas.android.com/apk/res/ + 應用的包名"
於是使用時就寫成:
authcodeview:titleText="3712"
authcodeview:titleTextColor="#00ffff"
authcodeview:titleTextSize="40sp"
順便附上系統 attrs 自定義的路徑圖:

先看一段代碼:
/** * 獲得我自定義的樣式屬性 * * @param context * @param attrs * @param defStyle */ public AuthCodeView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); /** * 獲得我們所定義的自定義樣式屬性 */ TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.AuthCodeView, defStyle, 0); //獲取在attr文件下,名字為AuthCodeView的declare-styleable屬性有幾個 int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { //這個屬性可以不要,因為都是隨機產生 case R.styleable.AuthCodeView_titleText: mTitleText = a.getString(attr); break; case R.styleable.AuthCodeView_titleTextColor: // 默認顏色設置為黑色 mTitleTextColor = a.getColor(attr, Color.BLACK); break; case R.styleable.AuthCodeView_titleTextSize: // 默認設置為16sp,TypeValue也可以把sp轉化為px mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); break; } } a.recycle(); }
這裡 TypedArray 的作用就是資源的映射。R.styleable.AuthCodeView 是不是有點眼熟?它對應的正是 declare-styleable 中定義的名字。而 R.styleable.AuthCodeView_titleText 的命名規則,就是「集合名 + 下劃線 + 屬性名」。透過它,我們就能把 XML 中設置的屬性值映射到 class 裡,取值時相當直觀。
如果對生成的 ID 有疑惑,翻一翻自動生成的 R 文件就一清二楚了。
本文先寫到這裡,下一篇將帶來續集——用自定義屬性打造一個隨機驗證碼的 Custom View,敬請期待。
Android 應用資源全解析:從 res 目錄到 StateListDrawable 與 AnimationDrawable
Java 初學者常把 hello、123 這類字面值直接寫進程式碼,過一陣子回頭看,往往已經想不起來當初為什麼這樣定義。有經驗的人會改用常數,例如 ResultSet.T
學習 Android Studio 開發工具之 Activity 與 Fragment 通信
開篇先介紹幾個放在眼前卻常被忽略的快捷鍵,它們能充分展現 Android Studio 強大的搜索能力,大幅提升大工程的開發維護效率。 雙擊 Shift:喚出 Searc
Android 實現智能機器人聊天完整實作
背景:關於實作聊天機器人,其實是個偶然的機會。公司需要做一個 iOS 版的機器人,用於自動購物,於是 iOS 部門就研發了一個。我覺得這種機器人挺有意思,想搞清楚背後到底
Android ContentProvider 自定義提供者與跨應用程式增刪改查
ContentProvider 的核心概念 ContentProvider 是 Android 四大元件之一,主要用途是讓不同應用程式安全地共享資料。提供者會將資料封裝在