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

Android 自定義屬性入門:TypedArray 用法詳解

編輯:關於 Android 程式設計

自定義 View 時,長寬等屬性通常在布局檔中設定,例如 android:layout_height="wrap_content"。除此之外,我們也能自定義屬性,使用時就能寫成 myapp:myTextSize="20sp" 這樣的形式。

values/attrs.xml

首先要建立變數。新增一個 values/attrs.xml(檔名可自訂,但須放在 values 目錄下):

<?xml version="1.0" encoding="utf-8"?>

<resources>

<declare-styleable name="MyView">

<attr name="textSize" format="dimension" />

</declare-styleable>

</resources>

其中 resources 是根標籤,可定義多個 declare-styleable;name 定義變數名稱,下面可再宣告多個屬性。以 <attr name="textSize" format="dimension"/> 來說,屬性名為 textSize,format 指定型別為 dimension(尺寸值)。

format 還可指定其他型別:reference(引用資源 ID)、string(字串)、color(顏色值)、dimension(尺寸值)、boolean(布爾值)、integer(整型)、float(浮點)、fraction(百分比)、enum(枚舉)、flag(位運算)。

在布局中使用

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"

xmlns:myapp="https://schemas.android.com/apk/res/com.eyu.attrtextdemo"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:orientation="vertical">

<us.yydcdut.MyView

android:layout_height="wrap_content"

android:layout_width="wrap_content"

myapp:textSize="20sp"

myapp:myColor="#324243"/>

</LinearLayout>

關鍵在於多了一行 xmlns:myapp="...",命名空間後面接的是你的 package 名稱,如此一來就能用 myapp:textSize 與 myapp:myColor 設定自定義屬性。

obtainStyledAttributes 讀取屬性

在 View 建構時,透過 context.obtainStyledAttributes 取得一個 TypedArray,再由它來讀取屬性設定。最常用的單參數版本,參數直接從 styleable 取得:

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);

使用完畢務必呼叫 recycle(),否則這次的設定會影響到下一次使用。

完整範例:

public class MyView extends View{

public Paint paint;

public MyView(Context context, AttributeSet attrs) {

super(context, attrs);

paint = new Paint();

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);

int textColor = a.getColor(R.styleable.MyView_myColor, 003344);

float textSize = a.getDimension(R.styleable.MyView_myTextSize, 33);

paint.setTextSize(textSize);

paint.setColor(textColor);

a.recycle();

}

@Override

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

paint.setStyle(Style.FILL);

canvas.drawText("aaaaaaa", 10, 50, paint);

}

}

透過 getColor、getDimension 等方法讀值並帶入預設值,就能讓自定義 View 擁有靈活可配置的屬性。

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