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

declare-styleable 用法解析:為自定義控制項加上專屬屬性

編輯:關於 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]。掌握這個規則,就能自由替自定義控制項擴充專屬屬性。

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