編輯:關於 Android 程式設計
在 Android 中開發自定義 View 時,如果能像系統控制項那樣透過 XML 設定自己的屬性,使用起來會直覺很多。declare-styleable 正是實現這個目標的關鍵。本文用一個簡單範例帶你走過整個流程。
(1)在 res/values 下定義 attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="my">
</declare-styleable>
</resources>
(2)在佈局檔案中使用,這裡需宣告自訂的 namespace,前綴 my 指向 app 的 package:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
xmlns:my="https://schemas.android.com/apk/res/com.example.xmpptest"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<com.example.xmpptest.MyTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
my:content="mycolor" >
</com.example.xmpptest.MyTextView>
</LinearLayout>
(3)在自定義控制項中讀取屬性。透過 obtainStyledAttributes 取得 TypedArray,再取出對應值,用完記得 recycle():
public class MyTextView extends TextView {
public MyTextView(Context context) {
this(context, null);
}
public MyTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.my);
String str = a.getString(R.styleable.my_content);
setText(str + "@@");
a.recycle();
}
}
(1)每個 attr 的 format 應指定明確型別,例如 string、integer、dimension、reference(參照 R 檔案)、color、enum、boolean 等;若有多種型別可用 | 分隔。以 enum 為例:
<declare-styleable name="my">
<enum name="fill_parent" value="-1" />
<enum name="wrap_content" value="-2" />
</declare-styleable>
(2)佈局檔案中的 XML namespace 命名規則為:xmlns:toolbar=https://schemas.android.com/apk/res/[packagename]。掌握這個規則,就能自由替自定義控制項擴充專屬屬性。
Android Adapter 使用教學(上):從 ArrayAdapter 認識列表與 View 重用機制
做 Android 應用,ListView 大概是最常打交道的控制項之一。微博、聯絡人,只要畫面上要一次列出多筆資料,就會想到它(另外還有 GridView)。那 Lis
Android 安全加密系列:非對稱加密與 RSA 實作全解
系列文章索引 Android 安全加密:對稱加密 Android 安全加密:非對稱加密 Android 安全加密:消息摘要 Message Digest Android
Android SQLite 資料庫實作入門:Helper、DAO 與 Activity 三層架構
Android 內建 SQLite,是應用在本地端儲存結構化資料最省事的選擇。要寫得清楚、後續好維護,通常會分成三層:一個繼承 SQLiteOpenHelper 的資料庫
Android ViewStub 用法詳解:需要時才載入的零尺寸佔位元件
ViewStub 的用途是在執行階段才把版面 lazily inflate 進來。官方文件的定義是: A ViewStub is an invisible, zero-s