Android之自定义View

在Android开发中,系统本身为我们提供了许多可供选择的UI控件,但是在有些情况下也是需要自定义一些控件的。比如UI中的柱状图、饼图等。而自定义View就需要明白它的原理了。

大体上分为三步onMeasure、onLayout、onDraw。大部分情况下我们只需要重写两个函数:onMeasure、onDraw。onMeasure负责对当前View的尺寸进行测量,onDraw负责将当前这个View绘制出来。

在自定义View时,构造函数也是必须的:

public CustomView(Context context){
        this.CustomView(context,null);
}

public CustomView(Context context,AttributeSet attr){
        this.CustomView(context,attr,0);
}

下面结合代码介绍以上三种方法:

1、onMeasure

思考:我在xml中已经设置好了宽、高了,在自定义View中有必要再次获取宽、高并设置它们吗?

答案是有必要的:比如我们在xml中指定layout_width和layout_height为wrap_content或者是match_parent。意思就是“包住内容”和“填充父布局给我们的空间”。这两个设置并没有指定具体的宽和高,而我们绘制到屏幕上的View是有具体的宽和高的。所以我们有必要在onMeasure()方法中来设置它的宽和高。

比如,我们希望在屏幕中显示一个正方形,而在XML布局中,它是一个长方形。

onMeasure函数原型

protected void onMeasure(int widthMeasureSpec,int heightMeasureSpec)

理解:

widthMeasureSpec和heightMeasureSpec两个参数包含宽和高的信息,而不仅仅有宽和高,还包括测量模式。

在设置宽高时有3个选择:wrap_contentmatch_parent固定尺寸,而测量模式也有三种:UNSPECFIED,EXACTLYAT_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);
 

测量模式:UNSPECFIED,EXACTLY,AT_MOST

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

测量模式与布局的wrap_content、match_parent和固定尺寸的对应关系:

match_parent---EXACTLY,match_parent就是利用父View给我们提供剩余空间,如果父View空间是确定的,那么它就是测量模式中就存放整数里面存放的尺寸。

wrap_content---AT_MOST,我们想要将大小设置为包裹我们的view内容,尺寸大小就是父View给我们作为参考的尺寸,只要不超过这个尺寸就可以,具体尺寸可以根据我们的需求去设定。

固定尺寸---EXACTLY

重写onMeasure函数

将当前View以正方形的形式展示,宽高设置为100dp

public int getSize(int defaultSize,int measureSpec){
    int mySize;
    int mode=MeasureSpec.getMode(measureSpec);
    int size=MeasureSpec.getSize(measureSpec);

    switch(mode){
        case MesasureSpec.UNSPECFIED:
                mySize=defaultSize;
                break;
        case MeasureSpec.AT_MOST:
                mySize=size;
                break;
        case MesaureSpec.EXACTLY:
                mySize=size;
                break;
        }
    }

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

        setMeasuredDimension(width,height);
    }
}


在XML布局中添加View:

<com.example.CustomView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#ff0000"
    />

重写onDraw函数:

假如要实现的是显示一个圆形:

@Override
protected void onDraw(Canvas canvas){
    //调用父ViewonDraw函数,因为这个View类为我们实现了一些基本的绘制功能
    super.onDraw(canvas);
    int r=getMesauredWidth()/2; //圆的半径
    int centerX=getLeft()+r;
    int centerY=getTop() +r;

    Paint paint=new Paint();//初始化最好放在外部
    paint.setColor(Color.RED);
    
    canvas.drawCircle(centerX,centerY,r,paint);
}

OK,基本上实现了自定义View的功能,这些只是基础,更复杂的功能需要在它们的基础之上进行改善,需要更深入的理解。

补充

自定义ViewGroup
自定义View的过程很简单,就那几步,可自定义ViewGroup可就没那么简单啦~,因为它不仅要管好自己的,还要兼顾它的子View。我们都知道ViewGroup是个View容器,它装纳child View并且负责把child View放入指定的位置。我们假象一下,如果是让你负责设计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>

看看最后的效果吧~

最后附上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;
        }
    }


}

猜你喜欢

转载自blog.csdn.net/weixin_38664232/article/details/84815237