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

Android 自定義視圖完整教程

編輯:關於 Android 程式設計

Android 的 UI 由 View(單個元素)與 ViewGroup(元素集合)構成。雖然系統內建了 Button、TextView、RelativeLayout 等豐富組件,但實際開發中難免需要打造量身訂做的視圖。透過繼承 View 或其子類並覆寫 onDraw、onTouchEvent 等方法,就能定義全新的行為。

自定義組件的五大面向

  • 繪圖(Drawing):覆寫 onDraw 控制渲染。
  • 互動(Interaction):以 onTouchEvent、手勢處理使用者操作。
  • 尺寸(Measurement):覆寫 onMeasure 決定內容維度。
  • 屬性(Attributes):在 XML 定義屬性,以 TypedArray 取值。
  • 持久化(Persistence):以 onSaveInstanceState / onRestoreInstanceState 保存與恢復狀態。

以下用一個「形狀選擇器」為例:使用者點擊時在方形、圓形、三角形之間切換。

定義視圖類

public class ShapeSelectorView extends View {
    // 必須提供接收 Context 與 AttributeSet 的構造器,供 UI 建立與編輯實例
    public ShapeSelectorView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
}

加入佈局

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <com.codepath.example.customviewdemo.ShapeSelectorView
        android:id="@+id/shapeSelector"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>

定義自定義屬性

先在 res/values/attrs.xml 宣告:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ShapeSelectorView">
        <attr name="shapeColor" format="color" />
        <attr name="displayShapeName" format="boolean" />
    </declare-styleable>
</resources>

每個屬性都有 name 與 format(如 color、dimension、boolean、integer、float)。定義好後即可透過 res-auto 命名空間使用:

<com.codepath.example.customviewdemo.ShapeSelectorView
    app:shapeColor="#7f0000"
    app:displayShapeName="true"
    android:id="@+id/shapeSelector"
    ... />

應用自定義屬性

public class ShapeSelectorView extends View {
    private int shapeColor;
    private boolean displayShapeName;

    public ShapeSelectorView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setupAttributes(attrs);
    }

    private void setupAttributes(AttributeSet attrs) {
        TypedArray a = getContext().getTheme().obtainStyledAttributes(
                attrs, R.styleable.ShapeSelectorView, 0, 0);
        try {
            shapeColor = a.getColor(R.styleable.ShapeSelectorView_shapeColor, Color.BLACK);
            displayShapeName = a.getBoolean(R.styleable.ShapeSelectorView_displayShapeName, false);
        } finally {
            a.recycle(); // TypedArray 為共用物件,必須回收
        }
    }
}

再補上 getter / setter,屬性變動時呼叫 invalidate() 與 requestLayout() 刷新顯示:

public boolean isDisplayingShapeName() { return displayShapeName; }
public void setDisplayingShapeName(boolean state) {
    this.displayShapeName = state; invalidate(); requestLayout();
}
public int getShapeColor() { return shapeColor; }
public void setShapeColor(int color) {
    this.shapeColor = color; invalidate(); requestLayout();
}

繪圖

所有繪圖都在 onDraw 中透過 Canvas 完成:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawRect(0, 0, shapeWidth, shapeHeight, paintShape);
    if (displayShapeName) {
        canvas.drawText("Square", shapeWidth + textXOffset, shapeHeight + textXOffset, paintShape);
    }
}
private void setupPaint() {
    paintShape = new Paint();
    paintShape.setStyle(Style.FILL);
    paintShape.setColor(shapeColor);
    paintShape.setTextSize(30);
}

計算尺寸

透過 onMeasure 依內容決定寬高,核心在於理解 MeasureSpec:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int textPadding = 10;
    int contentWidth = shapeWidth;
    int minw = contentWidth + getPaddingLeft() + getPaddingRight();
    int w = resolveSizeAndState(minw, widthMeasureSpec, 0);

    int minh = shapeHeight + getPaddingBottom() + getPaddingTop();
    if (displayShapeName) minh += textYOffset + textPadding;
    int h = resolveSizeAndState(minh, heightMeasureSpec, 0);

    setMeasuredDimension(w, h);
}

MeasureSpec 封裝了父佈局對子元素的測量要求,由大小與模式組成,模式有三種:UNSPECIFIED(未指定,子元素可任意大小)、EXACTLY(父元素決定確切大小)、AT_MOST(至多達到指定值)。resolveSizeAndState() 依期望大小與 MeasureSpec 回傳合適值,最後以 setMeasuredDimension() 生效。

切換形狀

在 onTouchEvent 中處理點擊切換:

private String[] shapeValues = { "square", "circle", "triangle" };
private int currentShapeIndex = 0;

@Override
public boolean onTouchEvent(MotionEvent event) {
    boolean result = super.onTouchEvent(event);
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
        currentShapeIndex++;
        if (currentShapeIndex > (shapeValues.length - 1)) currentShapeIndex = 0;
        postInvalidate();
        return true;
    }
    return result;
}

並在 onDraw 中依索引畫出對應形狀:

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    String shapeSelected = shapeValues[currentShapeIndex];
    if (shapeSelected.equals("square")) {
        canvas.drawRect(0, 0, shapeWidth, shapeHeight, paintShape);
        textXOffset = 0;
    } else if (shapeSelected.equals("circle")) {
        canvas.drawCircle(shapeWidth / 2, shapeHeight / 2, shapeWidth / 2, paintShape);
        textXOffset = 12;
    } else if (shapeSelected.equals("triangle")) {
        canvas.drawPath(getTrianglePath(), paintShape);
        textXOffset = 0;
    }
    if (displayShapeName) {
        canvas.drawText(shapeSelected, 0 + textXOffset, shapeHeight + textYOffset, paintShape);
    }
}

保存與恢復狀態

當配置改變(如旋轉屏幕)時,實作以下兩個方法即可自動保存與恢復:

@Override
public Parcelable onSaveInstanceState() {
    Bundle bundle = new Bundle();
    bundle.putParcelable("instanceState", super.onSaveInstanceState());
    bundle.putInt("currentShapeIndex", this.currentShapeIndex);
    return bundle;
}
@Override
public void onRestoreInstanceState(Parcelable state) {
    if (state instanceof Bundle) {
        Bundle bundle = (Bundle) state;
        this.currentShapeIndex = bundle.getInt("currentShapeIndex");
        state = bundle.getParcelable("instanceState");
    }
    super.onRestoreInstanceState(state);
}

完成這些邏輯後,即使手機配置改變,你的自定義視圖也能自動保存並還原狀態。

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