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

Android 自定義控制項入門(三):為自訂 View 加上自訂屬性

編輯:關於 Android 程式設計

前兩篇我們談了自定義 View 的起點,列舉了若干可覆寫的方法,並用同一個例子的兩種寫法說明「充分了解並積極覆寫 View 方法」的重要性。這一篇要解決的是更實際的問題:怎麼讓自訂 View 能在 XML 裡設定自己的屬性。

回想一下用原生控制項的體驗——在佈局檔裡改改顏色、調調大小,非常方便。自訂 View 若也能做到這點,複用性會大幅提升。以下用一個「移動小球」的例子說明完整流程。

一、format 型別有哪些

先在 values/ 目錄下確認是否有 attrs.xml,沒有就建立一個。宣告屬性時必須指定型別,可選值如下:

  • reference — 引用(指向某個資源)
  • color — 顏色
  • boolean — 布爾值
  • dimension — 尺寸值
  • float — 浮點數
  • integer — 整數
  • string — 字串
  • fraction — 百分比,例如 200%

二、定義 attrs.xml

這個例子定義四個屬性:半徑、顏色、起始 X、起始 Y。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MoveBallversion3">
        <attr name="BallRadius" format="float" />
        <attr name="BallColor" format="color" />
        <attr name="BallStartX" format="float" />
        <attr name="BallStartY" format="float" />
    </declare-styleable>
</resources>

declare-styleable 的 name 是後續在 Java 程式碼中定位這組屬性的識別名稱;內部每個 attr 的前半是屬性名,後半是型別。

三、在佈局中使用

使用時,控制項標籤要寫成「完整類名」的形式,並額外宣告一個命名空間:

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:myball="https://schemas.android.com/apk/res/com.example.customcomponentsdemo"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="這是 MoveBall 的 Demo 版本 3" />

    <com.example.customcomponentsdemo.component.DrawView3
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="10dp"
        myball:BallColor="@color/white"
        myball:BallRadius="20"
        myball:BallStartX="50"
        myball:BallStartY="200" />
</LinearLayout>

三段資訊缺一不可:包名(等同 manifest 中的 package)、類名,以及這個類必須是繼承自 View 的自訂類——無論它是專案內的原始碼,還是 libs 目錄下的 jar 包。

常見編譯錯誤

若報 error: No resource identifier found for attribute 'xxx' in package,多半是命名空間寫錯。早期需要填寫「https://schemas.android.com/apk/」加上控制項所在包路徑;ADT 升級後,這個路徑被簡化為:

xmlns:myball="https://schemas.android.com/apk/res-auto"

使用 res-auto 後,ADT 會自動去專案中尋找對應的 styleable 定義,不必再手寫包名,也避開了包名一改就編譯失敗的困擾。

四、在程式碼中讀取

重點全在構造方法裡。透過 obtainStyledAttributes 取得 TypedArray,再用「styleable 名稱_屬性名」的組合常數取值,最後記得 recycle:

public class DrawView3 extends View {
    private float CircleX;
    private float CircleY;
    private float CircleR;
    private int BallColor;

    public DrawView3(Context context, AttributeSet attrs) {
        super(context, attrs);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MoveBallversion3);
        CircleX = a.getFloat(R.styleable.MoveBallversion3_BallStartX, 10f);
        CircleY = a.getFloat(R.styleable.MoveBallversion3_BallStartY, 10f);
        CircleR = a.getFloat(R.styleable.MoveBallversion3_BallRadius, 10f);
        BallColor = a.getColor(R.styleable.MoveBallversion3_BallColor, 0x990000FF);
        a.recycle();
    }

    @Override
    public void onDraw(Canvas canvas) {
        Paint paint = new Paint();
        paint.setColor(BallColor);
        canvas.drawCircle(CircleX, CircleY, CircleR, paint);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        CircleX = event.getX();
        CircleY = event.getY();
        this.invalidate();
        return true;
    }
}

三個細節值得留意:

必須實作 (Context, AttributeSet) 構造方法。XML 膨脹時呼叫的就是這個版本,少了它會直接 inflate 失敗。

取值時務必帶預設值。例如 a.getFloat(..., 10f),這樣即使 XML 沒寫該屬性也不會拿到 0 導致小球消失。

recycle() 別忘。Ted 物件需要歸還,否則資源無法重複使用。

Activity 端就沒什麼特別了,照常 setContentView:

public class MoveBallActivity3 extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_moveball3);
    }
}

結語

這一講是這個系列的收尾。自定義 View 的路很長,但基礎流程就是這樣:宣告 styleable → 佈局中掛命名空間 → 構造方法中讀值並給預設 → onDraw 中呈現。掌握了這條主線,剩下的都是在此之上的變化與打磨。

系列源碼可於 CSDN 下載(ID: sunmc1204953974)。若內容有疏漏之處,歡迎指正。

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