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

Android 自定義屬性:attr.xml 與 TypedArray 的使用

編輯:關於 Android 程式設計

平常我們大多使用 android:xxx="..." 這樣的系統屬性。但有時我們需要自定義屬性,尤其是在開發自定義 View 的時候特別常見。整個流程大致分為以下幾個步驟。

1. 在 res/values 下定義 attrs.xml 檔案

在其中透過 <declare-styleable> 宣告自定義 View 的名稱與它所使用的屬性,例如 textColor、textSize 等。

2. 重寫自定義 View 的構造方法

透過 R.styleable.MyView 取得我們定義的屬性。這裡通常會使用 TypedArray 來讀取,並在最後呼叫 .recycle(),以保持該屬性在後續使用時的一致性。

public class MyView extends View {
    private Paint mPaint;
    private static final String mString = "oh,God!";

    public MyView(Context context) {
        super(context);
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mPaint = new Paint();
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        int textColor = a.getColor(R.styleable.MyView_textColor, 0xffffff); // 注意加上默認值
        float textSize = a.getDimension(R.styleable.MyView_textSize, 36);
        mPaint.setTextSize(textSize);
        mPaint.setColor(textColor);
        a.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPaint.setStyle(Paint.Style.FILL);
        // 畫一個矩形,前兩個是左上角座標,後兩個是右下角座標
        canvas.drawRect(new Rect(10, 10, 100, 100), mPaint);
        mPaint.setColor(Color.BLUE);
        canvas.drawText(mString, 10, 110, mPaint); // 繪製文字
    }
}

3. 在 XML 布局檔案中使用自定義屬性

使用時要特別注意命名空間前綴(這裡以 test 為例,指向應用的 package):

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:test="https://schemas.android.com/apk/res/com.example.viewdemo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <com.example.viewdemo.MyView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        test:textColor="#fff"
        test:textSize="40px" />
</LinearLayout>

運行後,畫面上便會出現一個由自定義屬性控制顏色與字號的矩形與文字:

透過 attrs.xml 定義屬性、在構造方法中讀取、再在布局中引用,這三個步驟就構成了 Android 自定義屬性的完整閉環,讓你的 View 也能像系統控件一樣靈活配置。

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