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

Android 自定義控件入門:View 的三個核心流程與一個實例

編輯:關於 Android 程式設計

前言

日常 Android 開發離不開控件。但系統提供的控件未必能滿足所有業務需求,這時候就需要自定義。本文先建立整體認知:自定義控件有哪些要求、實現步驟是什麼、底層繪制原理如何。

自定義控件的基本要求

1. 遵守 Android 標準規範:命名、可配置性、事件處理方式等,都要與系統控件保持一致的風格,讓使用者無需學習成本。
2. 支持在 XML 布局中配置屬性:通過自定義 declare-styleable 暴露參數。
3. 對交互有合適的反饋:按下、點擊、禁用等狀態要有視覺變化。
4. 具備兼容性:Android 版本碎片化嚴重,控件應在廣泛的系統版本上正常工作。

學習步驟

1. 理解 View 的工作原理
2. 編寫 View 類
3. 為 View 類增加自定義屬性
4. 實現繪制邏輯
5. 響應用戶交互
6. 提供自定義回調函數

兩種實現方式

方式一:繼承 ViewGroup
如 LinearLayout、FrameLayout、RelativeLayout。適合需要組合多個子控件的複合組件。

方式二:繼承 View
如 View、TextView、ImageView、Button。適合需要完全自定義繪製的單一控件。

實際上所有 ViewGroup 最終都繼承自 View,兩者的差別在於是否需要管理子元素。

繪制的三大流程

View 的顯示由三個流程依次完成:measure() → layout() → draw()。

1. Measure:測量尺寸

public final void measure(int widthMeasureSpec, int heightMeasureSpec)
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight)
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)

調用關係是:measure() 內部調用 onMeasure(),onMeasure() 完成測量後調用 setMeasuredDimension() 保存結果。

其中 measure() 和 setMeasuredDimension() 是 final 修飾的,子類不能重寫;自定義時只需重寫 onMeasure()。

關於 MeasureSpec:

MeasureSpec 是一個 32 位整型,高兩位是 mode,低 30 位是 size。三種 mode:

· UNSPECIFIED:父容器對子容器沒有任何限制,子容器想要多大就多大。通常出現在 ScrollView 等可滾動容器中。
· EXACTLY:父容器已經為子容器指定了確切尺寸,子容器必須服從(對應 match_parent 或具體 dp 值)。
· AT_MOST:子容器可以是指定大小以內的任意尺寸(對應 wrap_content)。

2. Layout:確定位置

public void layout(int l, int t, int r, int b)
protected boolean setFrame(int left, int top, int right, int bottom)
protected void onLayout(boolean changed, int left, int top, int right, int bottom)

layout() 通過調用 setFrame(l, t, r, b) 來確定自身在父容器中的四邊座標。而 onLayout() 只在自定義 ViewGroup 中才需要重寫——用來擺放子 View;單個 View 無子元素,不必關心。

3. Draw:繪製內容

public void draw(Canvas canvas)
protected void onDraw(Canvas canvas)

draw() 負責整套繪製流程(背景、內容、子 View、修飾層),onDraw() 是我們真正需要重寫的地方。在 View 類中 onDraw() 是空實現,ImageView 之所以能顯示圖片,就是因為它重寫了這個方法。若自定義的是 ViewGroup,通常不需要重寫。

實例:圓形百分比控件

需求很常見:一個圓形,用弧長表示百分比進度。這裡以繼承 View 為例。

public class PercentView extends View {

    private final static String TAG = PercentView.class.getSimpleName();
    private Paint mPaint;

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

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

    public PercentView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        Log.e(TAG, "onMeasure--widthMode-->" + widthMode);
        switch (widthMode) {
            case MeasureSpec.EXACTLY:
                break;
            case MeasureSpec.AT_MOST:
                break;
            case MeasureSpec.UNSPECIFIED:
                break;
        }
        Log.e(TAG, "onMeasure--widthSize-->" + widthSize);
        Log.e(TAG, "onMeasure--heightMode-->" + heightMode);
        Log.e(TAG, "onMeasure--heightSize-->" + heightSize);
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        Log.e(TAG, "onLayout");
    }

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

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.GRAY);
        // FILL 填充,STROKE 描邊,FILL_AND_STROKE 填充和描邊
        mPaint.setStyle(Paint.Style.FILL_AND_STROKE);

        int width = getWidth();
        int height = getHeight();
        Log.e(TAG, "onDraw---->" + width + "*" + height);

        float radius = width / 4;
        canvas.drawCircle(width / 2, height / 2, radius, mPaint);

        mPaint.setColor(Color.BLUE);
        RectF oval = new RectF(width / 2 - radius, height / 2 - radius,
                width / 2 + radius, height / 2 + radius);
        // 用於定義圓弧的形狀和大小的界限
        canvas.drawArc(oval, 270, 120, true, mPaint);
        // 根據進度畫圓弧
    }
}

布局中使用:

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

    <com.whoislcj.views.PercentView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp" />
</LinearLayout>

顯示效果:

如果把寬高改成固定值:

<com.whoislcj.views.PercentView
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_margin="10dp" />

效果就變成:

這個對比很直觀地說明了 MeasureSpec 的作用:wrap_content 時走 AT_MOST,尺寸由父容器給的上限決定;指定 150dp 時走 EXACTLY,控件必須服從。

這份代碼可以更好的地方

示例代碼重在演示原理,實戰中需要改進:

1. Paint 不應在 onDraw 中創建。示例每次都 new Paint(),而 onDraw 可能一幀調用多次,這會造成大量臨時對象,加劇 GC、導致掉幀。正確做法是作為成員變量在構造函數中初始化一次。

2. 應該做成正方形。圓形控件要求寬高相等,否則會畫成橢圓。可以在 onMeasure 中取寬高的最小值:

int size = Math.min(widthSize, heightSize);
setMeasuredDimension(size, size);

3. 進度應該可配置。把 120 度硬編碼是沒法用的。應通過自定義屬性傳入:

// res/values/attrs.xml
<declare-styleable name="PercentView">
    <attr name="percent" format="integer" />
    <attr name="circleColor" format="color" />
    <attr name="progressColor" format="color" />
    <attr name="strokeWidth" format="dimension" />
</declare-styleable>

// 代碼中讀取
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PercentView);
mPercent = a.getInteger(R.styleable.PercentView_percent, 0);
a.recycle();   // 務必調用

4. 起始角度應可配置。示例從 270 度(12 點鐘方向)開始順時針,這符合大部分設計規範。但有些設計稿要求從 3 點鐘方向起,做成可配置更通用。

5. 應該支持動畫過渡。進度突變會很生硬。可以用 ValueAnimator 驅動進度值平滑變化,配合 postInvalidateOnAnimation() 逐幀刷新。

6. 提供點擊等交互回調。如果控件需要響應點擊,應在構造函數中設置 setOnClickListener 或重寫 onTouchEvent,並通過接口把事件拋給外部。

7. 注意硬件加速下的限制。某些 Canvas API(如 setDrawTextOnPath、部分 Xfermode)在硬件加速下行為與軟件渲染不同,遇到顯示異常時可考慮 setLayerType(View.LAYER_TYPE_SOFTWARE, null)。

小結

自定義控件的骨架就是這三步:onMeasure 決定多大,onLayout 決定放哪(ViewGroup 才需要),onDraw 決定長什麼樣。

下一篇會進一步講解如何為自定義 View 添加可配置的 XML 屬性,以及如何處理自定義事件回調。

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