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

Android 自定義 View 入門:三種實現路線與自定義屬性的完整流程

編輯:關於 Android 程式設計

自定義 View 是 Android 開發的必備技能。實作路線大致有三種,而「讓自定義 View 能在 XML 中設定屬性」則是從玩具走向可複用元件關鍵的一步。

一、三種實現方式

  1. 繼承 ViewGroup 或 Layout:自行決定子 View 的位置與尺寸,把多個元件組合成複合元件。
  2. 繼承既有的 Widget View:在現成元件的基礎上擴充功能,改動最小、成本最低。
  3. 繼承 View:完全自幹 onDraw、onMeasure,自由度最高但工作量也最大。

二、建構子怎麼寫

public CustomView2(Context context) {
    // 純程式碼 new 出來時使用
    super(context);
}

public CustomView2(Context context, AttributeSet attrs) {
    // 在 XML 中使用時,系統呼叫的是這個
    super(context, attrs);
}

public CustomView2(Context context, AttributeSet attrs, int defStyle) {
    // 需要指定預設樣式時,由上一個建構子手動轉呼
    super(context, attrs, defStyle);
}

其中 attrs 代表該 View 的屬性集合,defStyle 是預設屬性資源集的 id。

三、定義自定義屬性

在 res/values/attrs.xml 中用 declare-styleable 宣告:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="customview">
        <!-- 屬性可以是 string 或資源引用,如 @drawable/img -->
        <!-- 支援的型別:string、boolean、integer、float、color、dimension、fraction -->
        <!-- 顏色寫法:#rgb / #rrggbb / #argb / #aarrggbb -->

        <!-- enum:單選整數值 -->
        <attr name="season">
            <enum name="spring" value="1" />
            <enum name="summer" value="2" />
        </attr>

        <!-- flag:可用 | 組合成位元 -->
        <attr name="flags">
            <flag name="spring" value="4" />
            <flag name="summer" value="8" />
        </attr>
    </declare-styleable>
</resources>

四、在佈局中使用

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

    <!-- xmlns:custom 指向 com.stone 套件,對應 declare-styleable 中的屬性 -->
    <LinearLayout
        android:layout_width="150dp"
        android:layout_height="150dp">

        <com.stone.view.CustomView1
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            custom:score="60%"
            custom:rotation="-45"
            custom:color="#3f00ff00" />
    </LinearLayout>

    <com.stone.view.CustomView2
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <!-- 若自定義 view 是內部類別,要用 view 標籤並指定 class 屬性 -->
    <view
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        class="com.stone.view.CustomView1$Custom1" />
</LinearLayout>

順帶一提,wrap_content 對應的測量模式是 MeasureSpec.AT_MOST,match_parent 則是 MeasureSpec.EXACTLY,這在自訂 onMeasure 時會用到。

五、在程式碼中解析屬性

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

    // 系統會自動在 declare-styleable 的 name 前加上套件前綴
    TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.customview1);

    int color = array.getColor(R.styleable.customview1_color, Color.WHITE);
    float rotation = array.getFloat(R.styleable.customview1_rotation, 0f);
    float score = array.getFraction(R.styleable.customview1_score, 0, 13, 10);

    array.recycle();   // 一定要回收,否則會浪費資源

    setBackgroundColor(color);
}

六、幾個容易忽略的重點

  • 命名空間值要填自己的套件名:xmlns:custom 後面接的是「宣告屬性的那個專案套件名稱」,寫錯就找不到屬性。
  • R.styleable 的命名規則:屬性名稱會被加上 declare-styleable 的 name 作為前綴,例如 styleable 名為 customview1,取 color 時要寫 R.styleable.customview1_color。
  • getFraction 的三個參數:分別是索引、母數(base)與分子倍率(pbase),用於百分比型別(如 "60%")的換算。
  • recycle 不可省:TypedArray 是共用資源池的物件,不回收會導致後續 obtainStyledAttributes 失敗。
  • 屬性宣告可重用:多個 styleable 需要同一組屬性時,可先用 attr 宣告再在各處 reference,避免重複定義。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved