自定义View实践篇(1)- 自定义单一View

1. 简介

前面分析了一大堆原理:
自定义View原理篇(1)- measure过程
自定义View原理篇(2)- layout过程
自定义View原理篇(3)- draw过程
现在来看看是如何实现自定义View:

2.自定义View的分类

自定义View可以分为两大类,一种是自定义单一View,另一种是自定义ViewGroup。具体如下图所示:

类型 实现 目的
自定义单一View 继承系统已有View
如:TextView
扩展已有View的功能
继承View 实现一些不规则效果
自定义ViewGroup 继承系统已有ViewGroup
如:LinearLayout
扩展已有ViewGroup的功能
组合View功能
继承ViewGroup 实现自定义布局

本章主要介绍一下自定义单一View,自定义ViewGroup下一章来说明。

3.自定义单一View

自定义单一View又分为两类,一类是继承系统已有View,另一类是直接继承View类,我们分开来看下。

3.1 继承系统已有View

这种方式可以去扩展系统已有View的功能,比如要显示一个圆形的ImageView等等,都可以通过这种方式去实现。
我们这里的例子就简单点,给一个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();//创建画笔
        mPaint.setColor(Color.RED);// 设置画笔颜色
        mPaint.setTextSize(100);//创建字体大小
    }

    @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"/>

运行程序看看效果:


自定义View-WatermarkImageView.png

简单总结一下:继承系统已有View去扩展功能还是比较简单的,这种方法一般只需重写onDraw()即可,同时也无需支持wrap_contentpadding

3.2 继承View类

继承View类可以用来实现一些不规则效果,但是需要注意的是,这种方式不仅需要重写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();//创建画笔
        mPaint.setColor(mColor);//设置画笔颜色
    }

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

        // 设置wrap_content的默认宽高值
        // 默认宽高的设定并无固定依据,根据需要灵活设置
        // 类似TextView,ImageView等针对wrap_content均在onMeasure()对设置默认宽高值有特殊处理,具体细节请自行查看
        int mWidth = 400;
        int mHeight = 400;

        // 当测量模式是AT_MOST(即wrap_content)时设置默认值
        if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth, mHeight);

        // 宽或高其中一个模式为AT_MOST(即wrap_content)时,设置为默认值
        } 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()方法作相应的修改:

    @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系统的控件以android开头的比如android:layout_width等等,这些都是系统自带的属性。
为了方便使用自定义View,通常我们都会加上一些自定义属性,比如:为RoundRectView增加一个设置颜色的属性。
自定义View属性可以分为三个步骤:

  1. values目录下创建自定义属性的xml文件
  2. 在自定义View的构造方法中解析自定义属性的值
  3. 在布局文件中使用自定义属性

下面对每个步骤来进行详细的讲解:

3.2.3.1 在values目录下创建自定义属性的xml文件

values目录下创建attrs_round_rect_view.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--自定义属性集合:RoundRectView-->
    <!--在该集合下,可以设置不同的自定义属性-->
    <declare-styleable name="RoundRectView">
        <!--在attr标签下设置需要的自定义属性-->
        <!--此处定义了一个设置图形的颜色:round_rect_color属性,格式是color,代表颜色-->
        <!--格式有很多种,如资源id(reference)等等-->
        <attr name="round_rect_color" format="color"/>

    </declare-styleable>
</resources>

3.2.3.2 在自定义View的构造方法中解析自定义属性的值

我们修改一下RoundRectView的构造方法:

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

        // 加载自定义属性集合RoundRectView
        TypedArray typedArray=context.obtainStyledAttributes(attrs,R.styleable.RoundRectView);
        //解析RoundRectView属性集合的round_rect_color属性,如果没设置默认值为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属性,如果没设置默认值为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();//创建画笔
        mPaint.setColor(mColor);//设置画笔颜色
    }

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

        // 设置wrap_content的默认宽高值
        // 默认宽高的设定并无固定依据,根据需要灵活设置
        // 类似TextView,ImageView等针对wrap_content均在onMeasure()对设置默认宽高值有特殊处理,具体细节请自行查看
        int mWidth = 400;
        int mHeight = 400;

        // 当测量模式是AT_MOST(即wrap_content)时设置默认值
        if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth, mHeight);

            // 宽或高其中一个模式为AT_MOST(即wrap_content)时,设置为默认值
        } 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-->
    <!--在该集合下,可以设置不同的自定义属性-->
    <declare-styleable name="RoundRectView">
        <!--在attr标签下设置需要的自定义属性-->
        <!--此处定义了一个设置图形的颜色: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>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容