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

自定義 View 與 ViewGroup 實戰:彩虹進度條與九宮格相簿

編輯:關於 Android 程式設計

一、先理解 View 是什麼

Android 所有控制項都是 View 或其子類。View 本質上就是螢幕上的一塊矩形區域,用一個 Rect 來表示:left、top 決定它相對於父 View 的起點,width、height 決定自身大小。這四個值定下來,View 在螢幕上的位置就確定了,接著才開始繪製內容。

二、View 的繪製三步驟

1. Measure(測量)

先算出自己需要佔多大面積。View 對外暴露的接口是:

 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() 設定測量後的寬高,getSuggestedMinimumWidth() 則回傳 View 的最小寬度(高度有對應方法)。順帶一提,MeasureSpec 是 View 的內部靜態類,定義了 UNSPECIFIED、AT_MOST、EXACTLY 三個常數,分別對應 LayoutParams 中的三種情況。覆寫 onMeasure() 就能重新定義自己的寬高。

2. Layout(排版)

對 View 而言這一步很單純,暴露的方法是:

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

因為 View 沒有子 View 需要排列,所以這一步不需要做額外工作。(若是 ViewGroup,就必須在 onLayout() 中把所有子 View 的大小與位置安排好。)

3. Draw(繪製)

 protected void onDraw(Canvas canvas) { }

View 類預設的 onDraw() 裡一行程式都沒有,但它給了我們一張空白畫布。就像畫卷攤開、畫筆在手,最終畫出什麼,取決於你。

另外三個重要方法

  • requestLayout():觸發一次新的 layout 流程。
  • invalidate():觸發一次新的 draw 流程。
  • forceLayout():標記 View 在下次重繪時必須重新走 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();   // 用完一定要 recycle

         mPaint = new Paint();
         mPaint.setAntiAlias(true);
         mPaint.setColor(barColor);
         mPaint.setStrokeWidth(vSpace);
     }

     // draw 被呼叫的次數
     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();   // 回呼 onDraw,形成連續動畫
     }
 }

三個建構子的呼叫時機值得記一下:

  • View(Context):程式碼中 new View(context) 時呼叫。
  • View(Context, AttributeSet):在 XML 版面中被 inflate 時呼叫。
  • View(Context, AttributeSet, int):與上者類似,但額外帶有 style 屬性時呼叫。

你可能會疑惑:我把讀取屬性的程式寫在第三個建構子,但版面中並沒有加 style,照理說應該走第二個建構子?答案在第二個建構子裡的 this(context, attrs, 0)——它把呼叫轉發給了第三個建構子。這是避免程式重複的小技巧。

版面檔:

 <?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>

核心邏輯就是呼叫 drawLine(),每次把起點往前推進一點,並在方法結尾呼叫 invalidate() 讓 View 重跑 onDraw(),於是就形成了持續向前移動的進度條動畫。短短數十行,自訂 View 並不難。

五、自定義 ViewGroup

ViewGroup 是 View 的容器類,我們常用的 LinearLayout、RelativeLayout 都是它的子類。因為 ViewGroup 有多個子 View,整個流程比單一 View 複雜一些,但仍然是 measure、layout、draw 三步。

Measure

若 layout_width/layout_height 是 match_parent 或具體數值,直接呼叫 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();
     }
 }

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()。因為它本身通常只是容器、不需額外裝飾,所以 onDraw() 往往直接沿用預設實作即可。

LayoutParams

LayoutParams 儲存了子 View 加入 ViewGroup 時的參數資訊。自訂 ViewGroup 時,通常也要定義一個自己的 LayoutParams,做法是在類別內部新增一個繼承 ViewGroup.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;
 }

六、實例二:九宮格相簿(類微信朋友圈選圖)

做一個類似微信朋友圈的選圖控制項:點擊「+」可以持續加圖,最多 9 張。微信是四個一排,這裡做三個一排。

 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());   // 子 View 水平間距
     int vSpace = Utils.dpToPx(10, getResources());   // 子 View 垂直間距
     int childWidth = 0;
     int childHeight = 0;

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

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

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

     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(0));
     }

     @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();
             // 把左上角座標先算好存起來,layout 階段直接用
             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);
     }

     @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) {
             View newChild = new View(getContext());
             addView(newChild);
             mImageResArrayList.add(new Integer(0));
             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();
     }
 }

這裡有個值得學的技巧:在 onMeasure() 中就把每個子 View 的 left/top 算好存進自訂 LayoutParams,onLayout() 時直接取出使用即可,不必重複計算。因為子 View 都是正方形且固定三個一排,用 i % 3 與 i / 3 就能直接推出列與行號。

版面檔:

 <?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>

執行結果:

兩個實例合起來說明了一件事:自訂控制項的難點從來不是 API 不熟悉,而是把「測量 → 排版 → 繪製」這條流程想清楚。只要釐清自己在每一步該負責什麼,剩下的就是普通的程式碼工作。

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