Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 自訂 View 與 ViewGroup 的繪製原理與實作

編輯:Android 開發實例

先認識 View

Android 中所有控制項都是 View 或其子類。View 在螢幕上佔據的其實就是一個矩形區域,用 Rect 描述:left、top 是相對於父容器的起始點,width、height 是自己的寬高。這四個值決定了 View 的位置,位置確定後才開始繪製內容。

View 的三個繪製階段

Measure

先量一次自己需要多大面積,對外暴露的接口是:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {}

View 類別已提供基礎實作:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(
            getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}

public static int getDefaultSize(int size, int measureSpec) {
    int result = size;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);
    switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
    }
    return result;
}

核心是最後呼叫 setMeasuredDimension() 寫入測量結果。順帶一提,MeasureSpec 是 View 的靜態內部類別,定義了 UNSPECIFIED、AT_MOST、EXACTLY 三種模式,大致對應 LayoutParams 裡的 unspecified、wrap_content 與 match_parent(或明確 dp 值)。覆寫 onMeasure() 就能自訂尺寸計算規則。

Layout

對單一 View 而言這一步幾乎沒事可做:

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {}

因為沒有子 View 需要排列。若是 ViewGroup,就得在這裡把每個子 View 的位置算好,後面會再談。

Draw

protected void onDraw(Canvas canvas) {}

View 預設的 onDraw() 一行程式碼都沒有,等於遞給我們一張空白畫布。畫出什麼,取決於開發者。

另外三個常用方法:

  • requestLayout():重新觸發一次 layout 流程。
  • invalidate():重新觸發一次 draw 流程。
  • forceLayout():標記下次重繪時必須重新 layout。

自訂屬性

View 本身已具備 layout_width、layout_height、background 等屬性,實務上往往還需要自己的屬性。做法是在 values 目錄下的 attrs.xml 中宣告(檔名可自取,但用這個名字最規範)。以下範例會用到兩個長度與一個顏色:

<declare-styleable name="rainbowbar">
    <attr name="rainbowbar_hspace" format="dimension"></attr>
    <attr name="rainbowbar_vspace" format="dimension"></attr>
    <attr name="rainbowbar_color" format="color"></attr>
</declare-styleable>

實作一:Google 風格彩虹進度條

為了聚焦重點,這裡只用單一顏色,多色版本留給讀者自行擴充。

public class RainbowBar extends View {
    // 進度條顏色
    int barColor = Color.parseColor("#1E88E5");
    // 每一段的寬度
    int hSpace = Utils.dpToPx(80, getResources());
    // 每一段的粗細
    int vSpace = Utils.dpToPx(4, getResources());
    // 段與段之間的間距
    int space = Utils.dpToPx(10, getResources());

    float startX = 0;
    float delta = 10f;
    Paint mPaint;

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

    public RainbowBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RainbowBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // 讀取自訂屬性
        TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.rainbowbar, 0, 0);
        hSpace = t.getDimensionPixelSize(R.styleable.rainbowbar_rainbowbar_hspace, hSpace);
        vSpace = t.getDimensionPixelOffset(R.styleable.rainbowbar_rainbowbar_vspace, vSpace);
        barColor = t.getColor(R.styleable.rainbowbar_rainbowbar_color, barColor);
        t.recycle(); // 用完務必回收

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(barColor);
        mPaint.setStrokeWidth(vSpace);
    }
    // ... 其餘省略
}

三個建構子各自被呼叫的時機:

  1. new View(context) 這種程式碼建立時。
  2. 在 XML 布局中被 inflate 時(最常見)。
  3. XML 中帶有 style 屬性時,會走第三個建構子。

你可能會疑惑:既然布局裡沒有寫 style,為什麼屬性讀取放在第三個建構子卻仍然有效?因為第二個建構子用 this(context, attrs, 0) 委派給了第三個,所以屬性初始化集中寫在一處即可,也避免程式碼重複。

int index = 0;

@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    float sw = this.getMeasuredWidth();
    if (startX >= sw + (hSpace + space) - (sw % (hSpace + space))) {
        startX = 0;
    } else {
        startX += delta;
    }
    float start = startX;
    // 往後段繪製
    while (start < sw) {
        canvas.drawLine(start, 5, start + hSpace, 5, mPaint);
        start += (hSpace + space);
    }
    start = startX - space - hSpace;
    // 往前段補齊
    while (start >= -hSpace) {
        canvas.drawLine(start, 5, start + hSpace, 5, mPaint);
        start -= (hSpace + space);
    }
    if (index >= 700000) {
        index = 0;
    }
    invalidate();
}

布局檔:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:gravity="center"
    android:layout_marginTop="40dp"
    android:orientation="vertical" >

    <com.sw.demo.widget.RainbowBar
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:rainbowbar_color="@android:color/holo_blue_bright"
        app:rainbowbar_hspace="80dp"
        app:rainbowbar_vspace="10dp" >
    </com.sw.demo.widget.RainbowBar>
</LinearLayout>

原理很單純:反覆呼叫 canvas.drawLine(),每次把起點往前推進,方法結尾呼叫 invalidate() 讓自己再畫一次,於是就形成了持續向前流動的視覺效果。短短數十行,可見自訂 View 並不如想像中困難。

自訂 ViewGroup

ViewGroup 是 View 的容器,我們常用的 LinearLayout、RelativeLayout 都是它的子類。因為要照顧多個子 View,流程雖然同樣是 measure、layout、draw 三步,但每步都更複雜。

Measure

若 layout_width / layout_height 是 match_parent 或明確 dp 值,直接呼叫 setMeasuredDimension() 即可。若是 wrap_content 就麻煩了,必須遍歷所有子 View 逐一測量,再依排列規則推算容器本身的尺寸。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int childCount = this.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View child = this.getChildAt(i);
        this.measureChild(child, widthMeasureSpec, heightMeasureSpec);
        int cw = child.getMeasuredWidth();
        // int ch = child.getMeasuredHeight();
    }
}

getChildCount() 回傳子 View 數量,measureChild() 則呼叫子 View 自己的測量。

Layout

@Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
    int childCount = this.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View child = this.getChildAt(i);
        LayoutParams lParams = (LayoutParams) child.getLayoutParams();
        child.layout(lParams.left, lParams.top,
                lParams.left + childWidth, lParams.top + childHeight);
    }
}

child.layout(left, top, right, bottom) 用來決定子 View 的實際位置,四個參數的意義看變數名即可理解。

Draw

ViewGroup 在 draw 階段主要是依序呼叫子 View 的 onDraw()。作為純容器,本身通常不需要額外裝飾,直接沿用預設實作就好。

LayoutParams

LayoutParams 保存子 View 加入容器時的參數資訊。自訂 ViewGroup 時,一般也要定義自己的 LayoutParams,就像 SDK 中的 LinearLayout.LayoutParams、RelativeLayout.LayoutParams 那樣:

public static class LayoutParams extends ViewGroup.LayoutParams {
    public int left = 0;
    public int top = 0;

    public LayoutParams(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
    }

    public LayoutParams(int arg0, int arg1) {
        super(arg0, arg1);
    }

    public LayoutParams(android.view.ViewGroup.LayoutParams arg0) {
        super(arg0);
    }
}

接著覆寫這幾個方法,讓 ViewGroup 使用自訂的 LayoutParams:

@Override
public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new NinePhotoView.LayoutParams(getContext(), attrs);
}

@Override
protected android.view.ViewGroup.LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}

@Override
protected android.view.ViewGroup.LayoutParams generateLayoutParams(
        android.view.ViewGroup.LayoutParams p) {
    return new LayoutParams(p);
}

@Override
protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {
    return p instanceof NinePhotoView.LayoutParams;
}

實作二:九宮格選圖控件

做一個類似朋友圈發文選圖的控件:點擊「+」號可以持續加圖,最多九張。微信是四個一排,這裡示範三個一排(順帶一提,微信是用 TableLayout 實作的)。

public class NinePhotoView extends ViewGroup {
    public static final int MAX_PHOTO_NUMBER = 9;

    private int[] constImageIds = { R.drawable.girl_0, R.drawable.girl_1, R.drawable.girl_2,
            R.drawable.girl_3, R.drawable.girl_4, R.drawable.girl_5, R.drawable.girl_6,
            R.drawable.girl_7, R.drawable.girl_8 };

    int hSpace = Utils.dpToPx(10, getResources());
    int vSpace = Utils.dpToPx(10, getResources());
    int childWidth = 0;
    int childHeight = 0;

    ArrayList<Integer> mImageResArrayList = new ArrayList<Integer>(9);
    private View addPhotoView;

    public NinePhotoView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        TypedArray t = context.obtainStyledAttributes(attrs, R.styleable.NinePhotoView, 0, 0);
        hSpace = t.getDimensionPixelSize(R.styleable.NinePhotoView_ninephoto_hspace, hSpace);
        vSpace = t.getDimensionPixelSize(R.styleable.NinePhotoView_ninephoto_vspace, vSpace);
        t.recycle();

        // 預先放一個「+」按鈕
        addPhotoView = new View(context);
        addView(addPhotoView);
        mImageResArrayList.add(new Integer());
    }
}

拍照與相簿選圖不是本文重點,因此圖片直接寫死在程式碼裡。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int rw = MeasureSpec.getSize(widthMeasureSpec);
    int rh = MeasureSpec.getSize(heightMeasureSpec);
    childWidth = (rw - 2 * hSpace) / 3;
    childHeight = childWidth;

    int childCount = this.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View child = this.getChildAt(i);
        LayoutParams lParams = (LayoutParams) child.getLayoutParams();
        // 三個一排,利用取餘與整除算出左上角座標
        lParams.left = (i % 3) * (childWidth + hSpace);
        lParams.top = (i / 3) * (childWidth + vSpace);
    }

    int vw = rw;
    int vh = rh;
    if (childCount < 3) {
        vw = childCount * (childWidth + hSpace);
    }
    vh = ((childCount + 3) / 3) * (childWidth + vSpace);
    setMeasuredDimension(vw, vh);
}

由於每格都是正方形且固定三欄,用簡單的取餘與整除就能算出所有子 View 的座標,並把結果暫存在自訂 LayoutParams 的 left / top 中,供 layout 階段使用。

@Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
    int childCount = this.getChildCount();
    for (int i = 0; i < childCount; i++) {
        View child = this.getChildAt(i);
        LayoutParams lParams = (LayoutParams) child.getLayoutParams();
        child.layout(lParams.left, lParams.top,
                lParams.left + childWidth, lParams.top + childHeight);

        if (i == mImageResArrayList.size() - 1
                && mImageResArrayList.size() != MAX_PHOTO_NUMBER) {
            // 最後一格且未滿九張,設為「+」並掛上點擊事件
            child.setBackgroundResource(R.drawable.add_photo);
            child.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
                    addPhotoBtnClick();
                }
            });
        } else {
            child.setBackgroundResource(constImageIds[i]);
            child.setOnClickListener(null);
        }
    }
}

public void addPhoto() {
    if (mImageResArrayList.size() < MAX_PHOTO_NUMBER) {
        addView(new View(getContext()));
        mImageResArrayList.add(new Integer());
        requestLayout();
        invalidate();
    }
}

public void addPhotoBtnClick() {
    final CharSequence[] items = { "Take Photo", "Photo from gallery" };
    AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            addPhoto();
        }
    });
    builder.show();
}

核心就是依 measure 階段算好的 left / top 呼叫 layout();同時判斷是否已達九張上限,未達上限時把最後一格設為「+」並綁定點擊事件,點下去彈出對話框讓使用者選擇拍照或選照片。

Draw 階段不需覆寫,沿用預設即可。

布局檔:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:layout_marginTop="40dp"
    android:orientation="vertical" >

    <com.sw.demo.widget.NinePhotoView
        android:id="@+id/photoview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:ninephoto_hspace="10dp"
        app:ninephoto_vspace="10dp"
        app:rainbowbar_color="@android:color/holo_blue_bright" >
    </com.sw.demo.widget.NinePhotoView>
</LinearLayout>

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