Android View體系(九)自訂View

來源:互聯網
上載者:User

Android View體系(九)自訂View
前言

學習了以上的文章後,接下來我們來講講自訂View,自訂View一直被認為是高手掌握的技能,因為情況太多,想實現的效果又變化多端,但它也要遵循一定的規則,我們要講的就是這個規則,至於那些變化多端的酷炫的效果就由各位來慢慢發揮了。但是需要注意的是凡事都要有個度,自訂View畢竟不是規範的控制項,如果不設計好不考慮效能反而會適得其反,另外適配起來可能也會產生問題,筆者的建議是如果能用系統控制項的還是盡量用系統控制項。

1.自訂View簡介

自訂View按照筆者的劃分,分為兩大類,一種是自訂View,一種是自訂ViewGroup;其中自訂View又分為繼承View和繼承系統控制項兩種。這篇文章首先先瞭解下兩大類的其中一種:自訂View。

2.繼承系統控制項的自訂View

這種自訂View在系統控制項的基礎上進行拓展,一般是添加新的功能或者修改顯示的效果,一般情況下我們在onDraw()方法中進行處理。這裡舉一個簡單的例子:

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

這個自訂View繼承TextView,並且在onDraw()方法中畫了一條紅色的橫線,接下來在布局中引用這個InvalidTextView:

   

運行程式看看效果:

3.繼承View的自訂View

與上面的繼承系統控制項的自訂View不同,繼承View的自訂View實現起來要稍微複雜一些,不只是要實現onDraw()方法,而且在實現過程中還要考慮到wrap_content屬性以及padding屬性的設定;為了方便配置自己的自訂View還會對外提供自訂的屬性,另外如果要改變觸控的邏輯,還要重寫onTouchEvent()等觸控事件的方法。

簡單實現繼承View的自訂View

按照上面的例子我們再寫一個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屬性進行處理

如果我在布局檔案中設定pading屬性,發現沒有任何的作用,看來還得對padding屬性進行處理,只需要在onDraw()方法中稍加修改就可以了,在繪製正方形的時候考慮到padding屬性就可以了:

 @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開頭的比如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的自訂屬性組合,我們定義了rect_color屬性,它的格式為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();    }

最後修改布局檔案:

  

使用自訂屬性需要添加schemas: xmlns:app=”http://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);    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.