自定義View實(shí)踐篇(1)- 自定義單一View

1. 簡介

前面分析了一大堆原理:
自定義View原理篇(1)- measure過程
自定義View原理篇(2)- layout過程
自定義View原理篇(3)- draw過程
現(xiàn)在來看看是如何實(shí)現(xiàn)自定義View:

2.自定義View的分類

自定義View可以分為兩大類,一種是自定義單一View,另一種是自定義ViewGroup。具體如下圖所示:

類型 實(shí)現(xiàn) 目的
自定義單一View 繼承系統(tǒng)已有View
如:TextView
擴(kuò)展已有View的功能
繼承View 實(shí)現(xiàn)一些不規(guī)則效果
自定義ViewGroup 繼承系統(tǒng)已有ViewGroup
如:LinearLayout
擴(kuò)展已有ViewGroup的功能
組合View功能
繼承ViewGroup 實(shí)現(xiàn)自定義布局

本章主要介紹一下自定義單一View,自定義ViewGroup下一章來說明。

3.自定義單一View

自定義單一View又分為兩類,一類是繼承系統(tǒng)已有View,另一類是直接繼承View類,我們分開來看下。

3.1 繼承系統(tǒng)已有View

這種方式可以去擴(kuò)展系統(tǒng)已有View的功能,比如要顯示一個圓形的ImageView等等,都可以通過這種方式去實(shí)現(xiàn)。
我們這里的例子就簡單點(diǎn),給一個ImageView加一個水印:

public class WatermarkImageView extends ImageView {//繼承ImageView

    private Paint mPaint;

    public WatermarkImageView(Context context) {
        super(context);
        init();
    }

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

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

    //畫筆初始化
    private void init() {
        mPaint = new Paint();//創(chuàng)建畫筆
        mPaint.setColor(Color.RED);// 設(shè)置畫筆顏色
        mPaint.setTextSize(100);//創(chuàng)建字體大小
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //畫上水印
        canvas.drawText("四月葡萄園博客", 20, getHeight() - 20, mPaint);
    }
}

在布局中引用這個WatermarkImageView,引用自定義的View需要包名+View名

    <com.april.view.WatermarkImageView
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/tuseji"/>

運(yùn)行程序看看效果:


自定義View-WatermarkImageView.png

簡單總結(jié)一下:繼承系統(tǒng)已有View去擴(kuò)展功能還是比較簡單的,這種方法一般只需重寫onDraw()即可,同時也無需支持wrap_contentpadding

3.2 繼承View類

繼承View類可以用來實(shí)現(xiàn)一些不規(guī)則效果,但是需要注意的是,這種方式不僅需要重寫onDraw(),還需要自己去支持wrap_contentpadding,否則wrap_contentpadding將不起效。另外,為了方便使用這個自定義View,我們通常還會提供一些自定義的屬性。
這里我們以畫一個圓角矩形為例:

public class RoundRectView extends View {//繼承View
    private Paint mPaint;
    private int mColor=Color.RED;
    
    public RoundRectView(Context context) {
        super(context);
        init();
    }

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

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

    private void init() {
        mPaint = new Paint();//創(chuàng)建畫筆
        mPaint.setColor(mColor);//設(shè)置畫筆顏色
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //獲取View的寬高
        int width = getWidth();
        int height = getHeight();

        //畫圓角矩形
        RectF rectF = new RectF(0, 0, width, height);
        canvas.drawRoundRect(rectF, 50, 50, mPaint);
    }
}

在布局中引用這個RoundRectView

    <com.april.view.RoundRectView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"/>

需要注意的是,我們這里使用了wrap_contentpadding,我們先來看看效果:

自定義View-RoundRectView.png

可以看到,wrap_content沒有起到效果,這里跟match_parent一樣了,至于原因,可以看下這篇文章的分析:自定義View原理篇(1)- measure過程
同樣,padding也沒有生效。
所以,我們需要自己去支持wrap_contentpadding

3.2.1 支持wrap_content

支持wrap_content需重寫onMeasure():

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

        // 設(shè)置wrap_content的默認(rèn)寬高值
        // 默認(rèn)寬高的設(shè)定并無固定依據(jù),根據(jù)需要靈活設(shè)置
        // 類似TextView,ImageView等針對wrap_content均在onMeasure()對設(shè)置默認(rèn)寬高值有特殊處理,具體細(xì)節(jié)請自行查看
        int mWidth = 400;
        int mHeight = 400;

        // 當(dāng)測量模式是AT_MOST(即wrap_content)時設(shè)置默認(rèn)值
        if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth, mHeight);

        // 寬或高其中一個模式為AT_MOST(即wrap_content)時,設(shè)置為默認(rèn)值
        } else if (widthMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth, heightSize);
        } else if (heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSize, mHeight);
        }
    }

再來看看效果:

自定義View-RoundRectView-支持wrap_content.png

wrap_content生效了。

3.2.2 支持padding

支持padding需要在onDraw()方法作相應(yīng)的修改:

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //獲取左右上下的padding值
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();

        //View的寬高需要減去padding
        int width = getWidth() - paddingLeft - paddingRight;
        int height = getHeight() - paddingTop - paddingBottom;

        //畫圓角矩形
        RectF rectF = new RectF(0 + paddingLeft, 0 + paddingTop, width + paddingRight, height + paddingBottom);
        canvas.drawRoundRect(rectF, 50, 50, mPaint);
    }

再來看看效果:

自定義View-RoundRectView-支持padding.png

padding也生效了。

3.2.3 自定義View屬性

Android系統(tǒng)的控件以android開頭的比如android:layout_width等等,這些都是系統(tǒng)自帶的屬性。
為了方便使用自定義View,通常我們都會加上一些自定義屬性,比如:為RoundRectView增加一個設(shè)置顏色的屬性。
自定義View屬性可以分為三個步驟:

  1. values目錄下創(chuàng)建自定義屬性的xml文件
  2. 在自定義View的構(gòu)造方法中解析自定義屬性的值
  3. 在布局文件中使用自定義屬性

下面對每個步驟來進(jìn)行詳細(xì)的講解:

3.2.3.1 在values目錄下創(chuàng)建自定義屬性的xml文件

values目錄下創(chuàng)建attrs_round_rect_view.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--自定義屬性集合:RoundRectView-->
    <!--在該集合下,可以設(shè)置不同的自定義屬性-->
    <declare-styleable name="RoundRectView">
        <!--在attr標(biāo)簽下設(shè)置需要的自定義屬性-->
        <!--此處定義了一個設(shè)置圖形的顏色:round_rect_color屬性,格式是color,代表顏色-->
        <!--格式有很多種,如資源id(reference)等等-->
        <attr name="round_rect_color" format="color"/>

    </declare-styleable>
</resources>

3.2.3.2 在自定義View的構(gòu)造方法中解析自定義屬性的值

我們修改一下RoundRectView的構(gòu)造方法:

    public RoundRectView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // 加載自定義屬性集合RoundRectView
        TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.RoundRectView);
        //解析RoundRectView屬性集合的round_rect_color屬性,如果沒設(shè)置默認(rèn)值為Color.RED
        mColor=typedArray.getColor(R.styleable.RoundRectView_round_rect_color,Color.RED);
        //獲取資源后要及時釋放
        typedArray.recycle();
        
        init();
    }

3.2.3.3 在布局文件中使用自定義屬性

最后,在布局中用上:

<?xml version="1.0" encoding="utf-8"?>
<!--必須添加schemas聲明才能使用自定義屬性-->
<!--添加的是xmlns:app="http://schemas.android.com/apk/res-auto"-->
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff">

    <com.april.view.RoundRectView
        app:round_rect_color="#00ffff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"/>

</FrameLayout>

需要注意的是:使用自定義屬性需要添加schemas: xmlns:app=”http://schemas.android.com/apk/res-auto”,其中app是我們自定義的名字,也可以使用其他名字。使用時需要加上這個名字作為額前綴,如:app:round_rect_color="#00ffff"
我們再來看看效果:

自定義View-RoundRectView-自定義屬性.png

至此,一個功能比較完善的自定義View就完成了。

3.2.4 完整代碼

最后貼一下完整的代碼:
RoundRectView.java :

public class RoundRectView extends View {//繼承View
    private Paint mPaint;
    private int mColor = Color.RED;

    public RoundRectView(Context context) {
        super(context);
        init();
    }

    public RoundRectView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // 加載自定義屬性集合RoundRectView
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RoundRectView);
        //解析RoundRectView屬性集合的round_rect_color屬性,如果沒設(shè)置默認(rèn)值為Color.RED
        mColor = typedArray.getColor(R.styleable.RoundRectView_round_rect_color, Color.RED);
        //獲取資源后要及時釋放
        typedArray.recycle();

        init();
    }

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

    private void init() {
        mPaint = new Paint();//創(chuàng)建畫筆
        mPaint.setColor(mColor);//設(shè)置畫筆顏色
    }

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

        // 設(shè)置wrap_content的默認(rèn)寬高值
        // 默認(rèn)寬高的設(shè)定并無固定依據(jù),根據(jù)需要靈活設(shè)置
        // 類似TextView,ImageView等針對wrap_content均在onMeasure()對設(shè)置默認(rèn)寬高值有特殊處理,具體細(xì)節(jié)請自行查看
        int mWidth = 400;
        int mHeight = 400;

        // 當(dāng)測量模式是AT_MOST(即wrap_content)時設(shè)置默認(rèn)值
        if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth, mHeight);

            // 寬或高其中一個模式為AT_MOST(即wrap_content)時,設(shè)置為默認(rèn)值
        } else if (widthMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth, heightSize);
        } else if (heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSize, mHeight);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //獲取左右上下的padding值
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();

        //View的寬高需要減去padding
        int width = getWidth() - paddingLeft - paddingRight;
        int height = getHeight() - paddingTop - paddingBottom;

        //畫圓角矩形
        RectF rectF = new RectF(0 + paddingLeft, 0 + paddingTop, width + paddingRight, height + paddingBottom);
        canvas.drawRoundRect(rectF, 50, 50, mPaint);
    }
}

values/attrs_round_rect_view.xml :

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--自定義屬性集合:RoundRectView-->
    <!--在該集合下,可以設(shè)置不同的自定義屬性-->
    <declare-styleable name="RoundRectView">
        <!--在attr標(biāo)簽下設(shè)置需要的自定義屬性-->
        <!--此處定義了一個設(shè)置圖形的顏色:round_rect_color屬性,格式是color,代表顏色-->
        <!--格式有很多種,如資源id(reference)等等-->
        <attr name="round_rect_color" format="color"/>

    </declare-styleable>
</resources>

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<!--必須添加schemas聲明才能使用自定義屬性-->
<!--添加的是xmlns:app="http://schemas.android.com/apk/res-auto"-->
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#fff">

    <com.april.view.RoundRectView
        app:round_rect_color="#00ffff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"/>

</FrameLayout>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,461評論 6 532
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,538評論 3 417
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,423評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,991評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,761評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,207評論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,268評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,419評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,959評論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,653評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,901評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,678評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,978評論 2 374

推薦閱讀更多精彩內(nèi)容