【转载】自定义View,有这一篇就够了

为了扫除学习中的忙点,尽量多的覆盖Android知识的边边角角,决定对自定义View作一个稍微全面一点的使用方法总结,在内容上面并无什么独特的地方,其余大神们博客上面基本上都有讲这方面的内容,若是你对自定义View很熟了,那么就不用往下看啦~。若是对自定义View不是很熟,或者说不少内容忘记了想复习一下,更或者说是历来没用过,欢迎和我一块儿重温这方面的知识,或许个人博文更复合你的胃口呢(__) 嘻嘻......java


1.自定义View

首先咱们要明白,为何要自定义View?主要是Android系统内置的View没法实现咱们的需求,咱们须要针对咱们的业务需求定制咱们想要的View。自定义View咱们大部分时候只须要重写两个函数:onMeasure()和onDraw()。onMeasure负责对当前View的尺寸进行测量,onDraw负责把当前这个View绘制出来。固然了,你还得写至少2个构造函数:android

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

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

1.1.onMeasure

咱们自定义的View,首先得要测量宽高尺寸。为何要测量宽高尺寸?我在刚学自定义View的时候很是没法理解!由于我当时以为,我在xml文件中已经指定好了宽高尺寸了,我自定义View中有必要再次获取宽高并设置宽高吗? 既然我自定义的View是继承自View类,google团队直接在View类中直接把xml设置的宽高获取,而且设置进去不就行了吗?那google为啥还让咱们作这样的"重复工做"呢?客官别急,立刻给您上茶~web


在学习Android的时候,咱们就知道,在xml布局文件中,咱们的layout_width和layout_height参数能够不写具体的尺寸,而是wrap_content或者是match_parent。其意思咱们都知道,就是将尺寸设置为"包住内容"和"填充父布局给咱们的全部空间"。这两个设置并无指定真正的大小,可视咱们绘制到屏幕上的View必须是要有具体点宽高的,正是由于这个缘由,咱们必须本身去处理和设置尺寸。固然了,View类给了默认的处理,可是若是View类的默认处理不知足咱们的要求,咱们就得重写onMeasure函数拉~。这里举个例子,好比咱们但愿咱们的View是个正方形,若是在xml中指定宽高为wrap_content,若是使用View类提供的measure处理方式,显然没法知足咱们的需求~。canvas


先看看onMeasure函数原型:ide

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 

参数中的widthMeasureSpec和heightMeasureSpec是个什么鬼?看起来很像width和height,没错,这两个参数就是包含宽和高的信息。什么?包含?难道还要其余信息?是的!它还包含测量模式,也就是说,一个int整数,里面放了测量模式和尺寸大小。那么一个数怎么放两个信息呢?咱们知道,咱们在设置宽高时有3个选择:wrap_content、match_parent以及指定固定尺寸,而测量模式也有3种:UNSPECIFIED、EXACTLY、AT_MOST,固然,他们并非一一对应关系哈,这三种模式后面我会详细介绍,但测量模式并不是就是这3种状况,而若是使用二进制,咱们只须要使用2个bit就能够作到,由于2个bit取值范围是[0,3]里面能够存放4个数足够咱们用了。那么Google是怎么把一个int同时放测量模式和尺寸信息呢?咱们知道int型数据占用32个bit,而Google实现的是,将int数据的前2个bit用于区分不一样的布局模式,后面30个bit存放的是尺寸的数据。函数


那咱们怎么从int数据中提取测量模式和尺寸呢?放心,不用你每次都要写一次移位<<和取且& 操做,Android内置类MeasureSpec帮咱们写好拉~,咱们只需按照下面方法就能够拿到拉:布局

int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);

爱思考的你确定会问,既然咱们能经过widthMeasureSpec拿到宽度尺寸大小,那咱们还要测量模式干吗?测量模式会不会是多余的?请注意:这里的尺寸大小并非最终咱们的View的尺寸大小,而是父View提供的参考大小。咱们看看测量模式,测量模式是干啥用个的呢?学习

测量模式 表示意思
UNSPECIFIED 父容器没有对当前View有任何限制,当前View能够任意取尺寸
EXACTLY 当前的尺寸就是当前View应该去的尺寸
AT_MOST 当前尺寸是当前View能取的最大尺寸

而上面的测量模式跟咱们的布局时的wrap_content、match_parent以及写成固定的尺寸有什么对应的关系呢?测试

match_parent——>EXACTLY。怎么理解呢?match_parent就是要利用父View给咱们提供的全部剩余空间,而父View剩余空间是肯定的,也就是这个测量模式的整数里面存放的尺寸。
warp_content——>AT_MOST。怎么理解呢?就是咱们想要将大小设置为包裹咱们View内容,那么尺寸大小就是父View给咱们做为参考的尺寸,只要不超过这个尺寸就能够拉,具体尺寸就根据咱们的需求去设定。
固定尺寸(如100dp)——>EXACTLY。用户本身指定了尺寸大小,咱们就不用再去干涉了,固然是以指定的大小为主拉。google


1.2.动手重写onMeasure函数

上面讲了太多理论,咱们实际操做一下吧,感觉一下onMeasure的使用,假设咱们要实现这样一个效果:将当前的View以正方形的形式显示,即要宽高相等,而且默认的宽高值为100像素。就能够这样编写:

private int getMySize(int defaultSize, int measureSpec) {
        int mySize = defaultSize;

        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);

        switch (mode) {
            case MeasureSpec.UNSPECIFIED: {//若是没有指定大小,就设置为默认大小
                mySize = defaultSize;
                break;
            }
            case MeasureSpec.AT_MOST: {//若是测量模式是最大取值为size
                //咱们将大小取最大值,你也能够取其余值
                mySize = size;
                break;
            }
            case MeasureSpec.EXACTLY: {//若是是固定的大小,那就不要去改变它
                mySize = size;
                break;
            }
        }
        return mySize;
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMySize(100, widthMeasureSpec);
        int height = getMySize(100, heightMeasureSpec);

        if (width < height) {
            height = width;
        } else {
            width = height;
        }

        setMeasuredDimension(width, height);
}

咱们设置一下布局

<com.hc.studyview.MyView android:layout_width="match_parent" android:layout_height="100dp" android:background="#ff0000" />

看看使用了咱们自定义onMeasure函数后的效果:

 

enter description here

自定义View.png

 


若是咱们不重写onMeasure,效果则是以下:

 

enter description here

不重写onMeasure.png

 


1.3.重写onDraw

上面咱们学会了自定义尺寸大小,那么尺寸咱们会设定了,接下来就是把咱们想要的效果画出来吧~绘制咱们想要的效果很简单,直接在画板Canvas对象上绘制就好啦,过于简单,咱们以一个简单的例子去学习:假设咱们须要实现的是,咱们的View显示一个圆形,咱们在上面已经实现了宽高尺寸相等的基础上,继续往下作:

@Override
    protected void onDraw(Canvas canvas) {
        //调用父View的onDraw函数,由于View这个类帮咱们实现了一些
        // 基本的而绘制功能,好比绘制背景颜色、背景图片等
        super.onDraw(canvas);
        int r = getMeasuredWidth() / 2;//也能够是getMeasuredHeight()/2,本例中咱们已经将宽高设置相等了
        //圆心的横坐标为当前的View的左边起始位置+半径
        int centerX = getLeft() + r;
        //圆心的纵坐标为当前的View的顶部起始位置+半径
        int centerY = getTop() + r;

        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        //开始绘制
        canvas.drawCircle(centerX, centerY, r, paint);
    }

效果如图:

 

enter description here

显示效果.png

 


1.4.自定义布局属性

若是有些属性咱们但愿由用户指定,只有当用户不指定的时候才用咱们硬编码的值,好比上面的默认尺寸,咱们想要由用户本身在布局文件里面指定该怎么作呢?那固然是经过咱们自定义属性,让用户本身定义属性啦~


首先咱们须要在res/values/stayles.xml文件(若是没有请本身新建)里面声明一个咱们自定义的属性:

<resources>

    <!--name为声明的"属性集合"名,能够随便取,可是最好是设置为跟咱们的View同样的名称-->
    <declare-styleable name="MyView">
        <!--声明咱们的属性,名称为default_size,取值类型为尺寸类型(dp,px等)-->
        <attr name="default_size" format="dimension" />
    </declare-styleable>
</resources>

接下来就是在布局文件用上咱们的自定义属性啦~

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:hc="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent">

    <com.hc.studyview.MyView android:layout_width="match_parent" android:layout_height="100dp" hc:default_size="100dp" />

</LinearLayout>

注意:须要在根标签(LinearLayout)里面设定命名空间,命名空间名称能够随便取,好比hc,命名空间口面取的值是固定的:"htt://schemas.android.com/apk/res-auto"


最后就是在咱们的自定义的View里面把咱们自定义的属性的值取出来,在构造函数中,还记得AttributeSet属性吗?就是靠它帮咱们把布局里面的属性取出来:

private int defalutSize;
  public MyView(Context context, AttributeSet attrs) {
      super(context, attrs);
      //第二个参数就是咱们在styles.xml文件中的<declare-styleable>标签
        //即属性集合的标签,在R文件中名称为R.styleable+name
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);

        //第一个参数为属性集合里面的属性,R文件名称:R.styleable+属性集合名称+下划线+属性名称
        //第二个参数为,若是没有设置这个属性,则设置的默认的值
        defalutSize = a.getDimensionPixelSize(R.styleable.MyView_default_size, 100);

        //最后记得将TypedArray对象回收
        a.recycle();
   }

最后把MyView的完整代码附上:

package com.hc.studyview;

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.util.Log;
import android.view.MotionEvent;
import android.view.View;

/** * Package com.hc.studyview * Created by HuaChao on 2016/6/3. */
public class MyView extends View {

    private int defalutSize;

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

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        //第二个参数就是咱们在styles.xml文件中的<declare-styleable>标签
        //即属性集合的标签,在R文件中名称为R.styleable+name
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
        //第一个参数为属性集合里面的属性,R文件名称:R.styleable+属性集合名称+下划线+属性名称
        //第二个参数为,若是没有设置这个属性,则设置的默认的值
        defalutSize = a.getDimensionPixelSize(R.styleable.MyView_default_size, 100);
        //最后记得将TypedArray对象回收
        a.recycle();
    }


    private int getMySize(int defaultSize, int measureSpec) {
        int mySize = defaultSize;

        int mode = MeasureSpec.getMode(measureSpec);
        int size = MeasureSpec.getSize(measureSpec);

        switch (mode) {
            case MeasureSpec.UNSPECIFIED: {//若是没有指定大小,就设置为默认大小
                mySize = defaultSize;
                break;
            }
            case MeasureSpec.AT_MOST: {//若是测量模式是最大取值为size
                //咱们将大小取最大值,你也能够取其余值
                mySize = size;
                break;
            }
            case MeasureSpec.EXACTLY: {//若是是固定的大小,那就不要去改变它
                mySize = size;
                break;
            }
        }
        return mySize;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMySize(defalutSize, widthMeasureSpec);
        int height = getMySize(defalutSize, heightMeasureSpec);

        if (width < height) {
            height = width;
        } else {
            width = height;
        }

        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        //调用父View的onDraw函数,由于View这个类帮咱们实现了一些
        // 基本的而绘制功能,好比绘制背景颜色、背景图片等
        super.onDraw(canvas);
        int r = getMeasuredWidth() / 2;//也能够是getMeasuredHeight()/2,本例中咱们已经将宽高设置相等了
        //圆心的横坐标为当前的View的左边起始位置+半径
        int centerX = getLeft() + r;
        //圆心的纵坐标为当前的View的顶部起始位置+半径
        int centerY = getTop() + r;

        Paint paint = new Paint();
        paint.setColor(Color.GREEN);
        //开始绘制
        canvas.drawCircle(centerX, centerY, r, paint);
    }
}

2.自定义ViewGroup

自定义View的过程很简单,就那几步,可自定义ViewGroup可就没那么简单啦~,由于它不只要管好本身的,还要兼顾它的子View。咱们都知道ViewGroup是个View容器,它装纳child View而且负责把childView放入指定的位置。咱们假设一下,若是是让你负责设计ViewGroup,你会怎么去设计呢?


1.首先,咱们得知道各个子View的大小吧,只有先知道子View的大小,咱们才知道当前的ViewGroup该设置为多大去容纳它们。
2.根据子View的大小,以及咱们的ViewGroup要实现的功能,决定出ViewGroup的大小。
3.ViewGroup和子View的大小算出来了以后,接下来就是去摆放了吧,具体怎么去拜访呢?这得根据你定制的需求去摆放了,好比,你想让子View按照垂直顺序一个挨着一个放,或则会按照前后顺序一个叠一个去放,这是你本身决定的。
4.已经知道怎么去拜访还不行啊,决定了怎么拜访就是至关于把已有的空间"分割"成大大小小的空间,每一个控件对于一个子View,接下来就是把子View对号入座了,把它们放进它们该放的地方去。


如今就完成了ViewGroup的设计了,咱们来个具体的案例,将子View按从上到下垂直顺序一个挨着一个摆放,即模仿实现LinearLayout的垂直布局。


首先重写onMeasure,实现测量子View大小以及设定ViewGroup的大小:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //将全部的子View进行测量,这会触发每一个子View的onMeasure函数
        //注意要与measureChild区分,measureChild是对单个view进行测量
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int childCount = getChildCount();

        if (childCount == 0) {//若是没有子View,当前ViewGroup没有存在的意义,不用占用空间
            setMeasuredDimension(0, 0);
        } else {
            //若是宽高都是包裹内容
            if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
                //咱们将高度设置为全部子View的高度相加,宽度设为子View中最大的宽度
                int height = getTotleHeight();
                int width = getMaxChildWidth();
                setMeasuredDimension(width, height);

            } else if (heightMode == MeasureSpec.AT_MOST) {//若是只有高度是包裹内容
                //宽度设置为ViewGroup本身的测量宽度,高度设置为全部子View的高度总和
                setMeasuredDimension(widthSize, getTotleHeight());
            } else if (widthMode == MeasureSpec.AT_MOST) {//若是只有宽度是包裹内容
                //宽度设置为子View中宽度最大的值,高度设置为ViewGroup本身的测量值
                setMeasuredDimension(getMaxChildWidth(), heightSize);

            }
        }
    }
    /*** * 获取子View中宽度最大的值 */
    private int getMaxChildWidth() {
        int childCount = getChildCount();
        int maxWidth = 0;
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            if (childView.getMeasuredWidth() > maxWidth)
                maxWidth = childView.getMeasuredWidth();

        }

        return maxWidth;
    }

    /*** * 将全部子View的高度相加 **/
    private int getTotleHeight() {
        int childCount = getChildCount();
        int height = 0;
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            height += childView.getMeasuredHeight();

        }

        return height;
    }

代码中的注释我已经写得很详细,再也不对每一行代码进行讲解。上面的onMeasure将子View测量好了,以及把本身的尺寸也设置好了,接下来咱们去摆放子View吧~

@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();
        //记录当前的高度位置
        int curHeight = t;
        //将子View逐个摆放
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            int height = child.getMeasuredHeight();
            int width = child.getMeasuredWidth();
            //摆放子View,参数分别是子View矩形区域的左、上、右、下边
            child.layout(l, curHeight, l + width, curHeight + height);
            curHeight += height;
        }
    }

咱们测试一下,将咱们自定义的ViewGroup里面放3个Button,将这3个Button的宽度设置不同,把咱们的ViewGroup的宽高都设置为包裹内容wrap_content,为了看的效果明显,咱们给ViewGroup加个背景:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">
    <com.hc.studyview.MyViewGroup android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#ff9900">
        <Button android:layout_width="100dp" android:layout_height="wrap_content" android:text="btn" />
        <Button android:layout_width="200dp" android:layout_height="wrap_content" android:text="btn" />
        <Button android:layout_width="50dp" android:layout_height="wrap_content" android:text="btn" />
    </com.hc.studyview.MyViewGroup>
</LinearLayout>

看看最后的效果吧~

 

enter description here

自定义ViewGroup.png

 


是否是很激动咱们本身也能够实现LinearLayout的效果啦~~
最后附上MyViewGroup的完整源码:

package com.hc.studyview;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

/** * Package com.hc.studyview * Created by HuaChao on 2016/6/3. */
public class MyViewGroup extends ViewGroup {
    public MyViewGroup(Context context) {
        super(context);
    }

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

    /*** * 获取子View中宽度最大的值 */
    private int getMaxChildWidth() {
        int childCount = getChildCount();
        int maxWidth = 0;
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            if (childView.getMeasuredWidth() > maxWidth)
                maxWidth = childView.getMeasuredWidth();
        }
        return maxWidth;
    }

    /*** * 将全部子View的高度相加 **/
    private int getTotleHeight() {
        int childCount = getChildCount();
        int height = 0;
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            height += childView.getMeasuredHeight();

        }
        return height;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //将全部的子View进行测量,这会触发每一个子View的onMeasure函数
        //注意要与measureChild区分,measureChild是对单个view进行测量
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        int childCount = getChildCount();

        if (childCount == 0) {//若是没有子View,当前ViewGroup没有存在的意义,不用占用空间
            setMeasuredDimension(0, 0);
        } else {
            //若是宽高都是包裹内容
            if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
                //咱们将高度设置为全部子View的高度相加,宽度设为子View中最大的宽度
                int height = getTotleHeight();
                int width = getMaxChildWidth();
                setMeasuredDimension(width, height);
            } else if (heightMode == MeasureSpec.AT_MOST) {//若是只有高度是包裹内容
                //宽度设置为ViewGroup本身的测量宽度,高度设置为全部子View的高度总和
                setMeasuredDimension(widthSize, getTotleHeight());
            } else if (widthMode == MeasureSpec.AT_MOST) {//若是只有宽度是包裹内容
                //宽度设置为子View中宽度最大的值,高度设置为ViewGroup本身的测量值
                setMeasuredDimension(getMaxChildWidth(), heightSize);
            }
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int count = getChildCount();
        //记录当前的高度位置
        int curHeight = t;
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            int height = child.getMeasuredHeight();
            int width = child.getMeasuredWidth();
            child.layout(l, curHeight, l + width, curHeight + height);
            curHeight += height;
        }
    }
}

好啦~自定义View的学习到此结束,是否是发现自定义View如此简单呢?

做者:huachao1001
连接:http://www.jianshu.com/p/c84693096e41

相关文章
相关标签/搜索