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

Android 自訂元件完整教學:從繼承 View 到自訂屬性

編輯:關於 Android 程式設計

在 Android 開發過程中,系統內建的元件與屬性未必能滿足所有需求。遇到特殊情境時,我們就需要自己動手做一個自訂 View 與專屬屬性。

一、實作步驟

  1. 繼承 View 類別或其子類別。
  2. 覆寫 View 中的關鍵方法。
  3. 為自訂 View 增加屬性(有兩種做法)。
  4. 繪製元件(載入版面或直接在 Canvas 作畫)。
  5. 響應用戶事件。
  6. 視需求定義回呼函式。

二、哪些方法需要覆寫

onDraw()
View 中的 onDraw() 是個空函式,也就是說具體的視圖都必須覆寫它來完成自己的繪製。ViewGroup 則不需要實作它,因為作為容器它「沒有內容」;但必須實作 dispatchDraw(),告訴子 View 該怎麼畫自己。

onLayout()
主要供 ViewGroup 型別排版子視圖使用,在 View 中它是空函式。

onMeasure()
用於計算視圖大小(長與寬),並透過 setMeasuredDimension(width, height) 保存計算結果。

onTouchEvent()
定義觸控事件以響應用戶操作。

還有一些較少用到但值得知道的方法:

  • onKeyDown / onKeyUp:按鍵按下與放開。
  • onTrackballEvent:軌跡球事件。
  • onSizeChanged():元件尺寸改變時。
  • onFinishInflate():從 XML 載入並建立完界面之後的回呼。
  • onWindowFocusChanged(boolean):元件取得或失去焦點時。
  • onAttachedToWindow():元件被放入某個視窗時。
  • onDetachedFromWindow():元件被從視窗分離時。
  • onWindowVisibilityChanged(int):所屬視窗的可見性改變時。

三、自訂元件的三大方式

  1. 繼承已有的控制項:當要實作的元件與現有控制項在許多方面類似時,透過擴展既有控制項來滿足需求。
  2. 繼承一個版面檔:常用於自訂組合控制項。在建構子中透過 LayoutInflater 與 addView() 載入自訂元件的版面形成界面,不需要 onDraw()。
  3. 直接繼承 View:完全自己畫,透過 onDraw() 繪製出元件界面。

四、自訂屬性的兩種做法

做法一:直接在版面檔寫屬性,在建構子中取得

版面檔:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.demo.myView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        Text="@string/hello_world" />
</RelativeLayout>

取得屬性值:

public myView(Context context, AttributeSet attrs) {
    super(context, attrs);
    int textId = attrs.getAttributeResourceValue(null, "Text", 0);
    String text = context.getResources().getText(textId).toString();
}

這種寫法簡單,缺點是沒有型別檢查、也無法有完整的提示支援,只適合臨時或私有屬性。

做法二:建立 attrs.xml 正式宣告

在 res/values/ 下新增 attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="myView">
        <attr name="text" format="string" />
        <attr name="textColor" format="color" />
    </declare-styleable>
</resources>

format 可以使用的型別相當豐富:

  • reference:參考某一資源 ID
  • color:顏色值
  • boolean:布林值
  • dimension:尺寸值
  • float:浮點值
  • integer:整型值
  • string:字串
  • fraction:百分比
  • enum:列舉值,例如 <enum name="horizontal" value="0" />
  • flag:位元 OR 運算組合
  • 多型別:以 | 串接,例如 color|reference

加到版面檔時要先宣告命名空間:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:myview="https://schemas.android.com/apk/res-auto">

    <com.example.demo.myView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        myview:text="test"
        myview:textColor="#ff0000" />
</RelativeLayout>

命名空間的規則是:xmlns:前綴="https://schemas.android.com/apk/包名",也可以直接用 https://schemas.android.com/apk/res-auto 讓工具自動處理。使用時寫「前綴:屬性名」即可。

在建構子中透過 TypedArray 取得:

public myView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.myView);
    String text = a.getString(R.styleable.myView_text);
    int textColor = a.getColor(R.styleable.myView_textColor, Color.WHITE);
    a.recycle();
}

或者用遍歷的方式處理:

public myView(Context context, AttributeSet attrs) {
    super(context, attrs);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.myView);
    int n = a.getIndexCount();
    for (int i = 0; i < n; i++) {
        int attr = a.getIndex(i);
        switch (attr) {
            case R.styleable.myView_text:
                break;
            case R.styleable.myView_textColor:
                break;
        }
    }
    a.recycle();
}

五、實作範例:跟著手指移動的小球

跟隨手指移動的小球自訂 View 示範

要做這個效果,大致需要三個部分:在 res/values/ 下建立 attrs.xml 宣告屬性、一個繼承 View 並覆寫部分函式的自訂類別、一個承載它的容器版面。

1. 宣告屬性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="myView">
        <attr name="TextColor" format="color" />
    </declare-styleable>
</resources>

2. 自訂 View 類別

在建構子中取得屬性,並覆寫 onDraw() 與 onTouchEvent() 完成繪製與事件響應。

public class myView extends View {

    private final Paint p = new Paint();
    public float currentX = 50;
    public float currentY = 50;
    public int textColor;

    public myView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // 只有一個屬性時不必遍歷,直接取出 color 值
        // 把屬性放進資源檔,方便設定與複用
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.myView);
        textColor = array.getColor(R.styleable.myView_TextColor, Color.BLACK);
        array.recycle();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 畫一個藍色的圓
        p.setColor(Color.BLUE);
        canvas.drawCircle(currentX, currentY, 30, p);

        // 使用資源檔設定的文字顏色
        p.setColor(textColor);
        canvas.drawText("BY finch", currentX - 30, currentY + 50, p);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        currentX = event.getX();
        currentY = event.getY();
        invalidate();   // 觸發重新繪製
        return true;
    }
}

自訂 View 執行結果截圖

原理很單純:不斷更新目前座標並呼叫 invalidate() 重新繪製。要注意的是,使用 TypedArray 之後一定要呼叫 recycle(),否則會影響下一次取得屬性。

3. 加入版面檔

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    xmlns:myview="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="finch.scu.cn.myview.MainActivity">

    <finch.scu.cn.myview.myView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        myview:TextColor="#ff0000" />
</RelativeLayout>

4. MainActivity

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

結語

具體怎麼做,取決於具體需求。舉例來說,如果要做「側滑刪除」的 ListView,就可以繼承 ListView、監聽側滑事件、在滑動時顯示刪除按鈕來完成功能。

幾個通用原則值得記住:屬性盡量用 attrs.xml 正式宣告以获得型別支援;onDraw() 裡不要建立物件,也避免配置記憶體;invalidate() 會觸發重繪,在 onDraw() 中呼叫它會造成無限迴圈。

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