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

Android 自定義屬性完整指南:attrs、styleable 與 TypedArray

編輯:關於 Android 程式設計

自定義屬性的基本流程

自定義 View 想提供可配置屬性,通常需要三個步驟:定義屬性資源、在布局中宣告命名空間、在構造方法中讀取 TypedArray。

在 attrs.xml 中宣告屬性

<resources>
  <declare-styleable name="SwipeListView">
    <attr name="swipeMode" format="enum">
      <enum name="none" value="0" />
      <enum name="both" value="1" />
      <enum name="left" value="2" />
      <enum name="right" value="3" />
    </attr>
    <attr name="swipeOffsetLeft" format="dimension" />
  </declare-styleable>
</resources>

declare-styleable 是一組屬性的集合,方便管理同一個自定義 View 的所有配置。attr 的 format 可指定為 reference、string、color、boolean、dimension、float、integer、fraction、enum 或 flag。

在布局中使用自定義屬性

使用自定義屬性時,必須先宣告命名空間。現代 Android 專案通常使用 res-auto,避免硬編碼套件名稱。

<com.example.view.SwipeListView
  xmlns:swipe="https://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  swipe:swipeMode="both" />

在構造方法中讀取屬性

TypedArray array = getContext().obtainStyledAttributes(
  attrs,
  R.styleable.SwipeListView,
  defStyleAttr,
  defStyleRes
);
swipeMode = array.getInt(R.styleable.SwipeListView_swipeMode, 0);
array.recycle();

obtainStyledAttributes 的參數中,defStyleAttr 指向目前主題中的 style 引用,defStyleRes 則指向明確的 style 資源。一般優先級為:布局屬性、defStyleAttr、defStyleRes、程式碼預設值。

兩種常見寫法

第一種寫法是在雙參數構造中呼叫三參數構造,適合需要指定 defStyleAttr 的場景。第二種寫法是在每個構造中呼叫初始化方法,適合繼承系統控制項並保留預設樣式的場景。

另外,讀取屬性也可以逐項 get,或透過 getIndexCount 與 getIndex 動態判斷布局中實際使用了哪些屬性。後者能避免未使用屬性覆蓋預設值。

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