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

Android View 體系(九):動手打造屬於自己的自定義 View

編輯:關於 Android 開發

從零認識自定義 View

讀完前面幾篇關於 View 體系的文章後,終於輪到許多人既期待又頭痛的主題——自定義 View。之所以說它「高手必備」,是因為實現方式千變萬化、要的效果五花八門,但只要掌握了背後那套規則,剩下的創意就能自由發揮。這篇文章要談的,正是這套通用規則。

不過在動手之前,有句話得先放在心裡:凡事都講究分寸。自定義 View 畢竟不像系統控件那樣經過反覆打磨,如果事先沒有仔細設計、忽略了效能,反而容易適得其反,甚至在多螢幕適配上埋下地雷。所以筆者的建議很直接——能用系統現成控件的,就盡量別重造輪子。

自定義 View 的兩大門派

按照筆者的分類,自定義 View 大致可以分成兩類:自定義 View 與自定義 ViewGroup。而自定義 View 又能細分為「繼承 View」與「繼承系統控件」兩種。本文先聚焦其中的自定義 View,把這兩條路走通。

第一種:繼承系統控件

這一類的做法是在系統控件的基礎上做擴展,通常是加上新功能,或是調整顯示樣式,處理的重心大多落在 onDraw() 方法裡。下面用一個最直觀的例子開場——繼承 TextView,幫它畫上一條紅色橫線:

public class InvalidTextView extends TextView { private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); public InvalidTextView(Context context) { super(context); initDraw(); } public InvalidTextView(Context context, AttributeSet attrs) { super(context, attrs); initDraw(); } public InvalidTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initDraw(); } private void initDraw() { mPaint.setColor(Color.RED); mPaint.setStrokeWidth((float) 1.5); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int width = getWidth(); int height = getHeight(); canvas.drawLine(0, height / 2, width, height / 2, mPaint); } }

接著在佈局檔裡引用這個 InvalidTextView:

 

跑起來看看成果:

第二種:直接繼承 View

相較於繼承系統控件,直接繼承 View 會稍微複雜一些。你不只要實作 onDraw(),還得在過程中把 wrap_content 與 padding 這兩個屬性照顧到;如果想讓自定義 View 更好配置,通常還會對外開放自訂屬性;要是打算改動觸控邏輯,就得重寫 onTouchEvent() 這一類事件方法。

先把基礎版做出來

沿著前面的思路,我們寫一個 RectView 繼承 View,畫出一個正方形:

public class RectView extends View { private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private int mColor=Color.RED; public RectView(Context context) { super(context); initDraw(); } public RectView(Context context, AttributeSet attrs) { super(context, attrs); initDraw(); } public RectView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initDraw(); } private void initDraw() { mPaint.setColor(mColor); mPaint.setStrokeWidth((float) 1.5); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int width = getWidth(); int height = getHeight(); canvas.drawRect(0, 0, width, height, mPaint); } }

在佈局中引用 RectView:

 

執行看看:

讓 padding 真正生效

這時候如果你在佈局檔裡設了 padding,會發現完全沒反應。原因很簡單——我們在 onDraw() 裡根本沒把它算進去。只要在繪製時把四邊的內距一併考量即可:

 @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int paddingLeft=getPaddingLeft(); int paddingRight=getPaddingRight(); int paddingTop=getPaddingTop(); int paddingBottom=getPaddingBottom(); int width = getWidth()-paddingLeft-paddingRight; int height = getHeight()-paddingTop-paddingBottom; canvas.drawRect(0+paddingLeft, 0+paddingTop, width+paddingRight, height+paddingBottom, mPaint); }

改一下佈局,把 padding 加回來:

 

效果如下:

替 wrap_content 補上預設尺寸

再把 RectView 的寬度分別設成 wrap_content 與 match_parent,你會詫異地發現兩者效果一模一樣:

這背後的原因,可以參考筆者〈Android View 體系(七):從源碼解析 View 的 measure 流程〉一文。要解決這個問題,我們得在 onMeasure() 裡指定一組預設寬高,當偵測到 wrap_content 時就用這組值:

 @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int widthSpecSize=MeasureSpec.getSize(widthMeasureSpec); int heightSpecSize=MeasureSpec.getSize(heightMeasureSpec); if(widthSpecMode==MeasureSpec.AT_MOST&&heightSpecMode==MeasureSpec.AT_MOST){ setMeasuredDimension(400,400); }else if(widthSpecMode==MeasureSpec.AT_MOST){ setMeasuredDimension(400,heightSpecSize); }else if(heightSpecMode==MeasureSpec.AT_MOST){ setMeasuredDimension(widthSpecSize,400); } }

這裡要特別提醒:setMeasuredDimension() 接收的單位是 px,別搞混了。來看效果:

開放自訂屬性

系統控件裡那些以 android 開頭的屬性,例如 android:layout_width,都是內建的。為了讓 RectView 更好配置,我們也可以定義自己的屬性。首先在 values 目錄下建立 attrs.xml:

 <code class="hljs xml"><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E--> <resources> <declare-styleable name="RectView"> <attr format="color" name="rect_color"> </attr></declare-styleable> </resources></code>

這份設定定義了一組名為 RectView 的屬性集合,其中包含一個格式為 color 的 rect_color。接著在 RectView 的建構子裡把這個值解析出來:

 public RectView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray mTypedArray=context.obtainStyledAttributes(attrs,R.styleable.RectView); //提取RectView屬性集合的rect_color屬性,如果沒設置默認值為Color.RED mColor=mTypedArray.getColor(R.styleable.RectView_rect_color,Color.RED); //獲取資源後要及時回收 mTypedArray.recycle(); initDraw(); }

最後修改佈局檔:

 

使用自訂屬性前,記得加上命名空間 xmlns:app="https://schemas.android.com/apk/res-auto",其中的 app 是我們自己取的名字。最後把 app:rect_color 設為 android:color/holo_blue_light,成果如下:

最後附上 RectView 的完整程式碼,方便你對照:

package com.example.liuwangshu.mooncustomview; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.util.AttributeSet; import android.view.View; public class RectView extends View { private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private int mColor=Color.RED; public RectView(Context context) { super(context); initDraw(); } public RectView(Context context, AttributeSet attrs) { super(context, attrs); TypedArray mTypedArray=context.obtainStyledAttributes(attrs,R.styleable.RectView); //提取RectView屬性集合的rect_color屬性,如果沒設置默認值為Color.RED mColor=mTypedArray.getColor(R.styleable.RectView_rect_color,Color.RED); //獲取資源後要及時回收 mTypedArray.recycle(); initDraw(); } public RectView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initDraw(); } private void initDraw() { mPaint.setColor(mColor); mPaint.setStrokeWidth((float) 1.5); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec); int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec); int widthSpecSize=MeasureSpec.getSize(widthMeasureSpec); int heightSpecSize=MeasureSpec.getSize(heightMeasureSpec); if(widthSpecMode==MeasureSpec.AT_MOST&&heightSpecMode==MeasureSpec.AT_MOST){ setMeasuredDimension(400,400); }else if(widthSpecMode==MeasureSpec.AT_MOST){ setMeasuredDimension(400,heightSpecSize); }else if(heightSpecMode==MeasureSpec.AT_MOST){ setMeasuredDimension(widthSpecSize,400); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int paddingLeft = getPaddingLeft(); int paddingRight = getPaddingRight(); int paddingTop = getPaddingTop(); int paddingBottom = getPaddingBottom(); int width = getWidth() - paddingLeft - paddingRight; int height = getHeight() - paddingTop - paddingBottom; canvas.drawRect(0 + paddingLeft, 0 + paddingTop, width + paddingRight, height + paddingBottom, mPaint); } }

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