Android开发之自定义View

577 阅读8分钟

1 自定义view

为什么要自定义View?
主要是Android系统内置的View无法实现我们的需求,我们需要针对我们的业务需求定制我们想要的View。自定义View我们大部分时候只需重写两个函数:onMeasure()、onDraw()。onMeasure负责对当前View的尺寸进行测量,onDraw负责把当前这个View绘制出来。

1.1 view的构造函数

//如果View在Java代码中是new出来的,就会调用第一个构造函数
public View(Context context) {
    throw new RuntimeException("Stub!");
}

//如果View是在.xml里面声明的就会调用第二个构造函数
public View(Context context, @Nullable AttributeSet attrs) {
    throw new RuntimeException("Stub!");
}

public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    throw new RuntimeException("Stub!");
}

public View(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int         defStyleRes) {
    throw new RuntimeException("Stub!");
}

1.2 onMeasure

在自定义View的时候,首先得要测量宽高尺寸。为什么要测量宽高尺寸?
在xml布局文件中,layout_widthlayout_height参数可以不用写具体的尺寸,而是wrap_content(当前的控件大小能够刚好包含里面的内容)或者是match_parent(当前控件的大小和父布局的大小一样)。这两个设置并没有指定真正的大小,而绘制到屏幕上的View必须是要有具体的宽高的,正是因为这个原因,我们必须自己去处理和设置尺寸。
View类给了默认的处理,但是如果View类的默认处理不满足我们的要求,我们就得重写onMeasure方法。这里举个例子,比如我们需要的View是个正方形,如果在xml中指定宽高为wrap_content,如果使用View类提供的measure处理方式,是无法满足我们的需求。这个时候就需要重写onMeasure方法。

//view的onMeasure方法
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}

参数中的widthMeasureSpecheightMeasureSpec包含了宽和高的信息——测量模式和尺寸大小

可能有很多人想不通,一个int型整数怎么可以表示两个东西(测量模式和尺寸大小),一个int类型我们知道有32位。而模式有三种,要表示三种状 态,至少得2位二进制位。于是系统采用了最高的2位表示模式。如图:

image.png
最高两位是00的时候表示"未指定模式"。即MeasureSpec.UNSPECIFIED
最高两位是01的时候表示"'精确模式"。即MeasureSpec.EXACTLY
最高两位是11的时候表示"最大模式"。即MeasureSpec.AT_MOST

很多人一遇到位操作头就大了,为了操作简便,于是系统给我提供了一个MeasureSpec工具类。这个工具类有四个方法和三个常量(上面所示)供我们使用:
这个是由我们给出的尺寸大小和模式生成一个包含这两个信息的int变量,这里mode这个参数,传三个常量中的一个。
public static int makeMeasureSpec(int size, int mode)

这个是得到这个变量中表示的模式信息,将得到的值与三个常量进行比较。
public static int getMode(int measureSpec)

这个是得到这个变量中表示的尺寸大小的值。
public static int getSize(int measureSpec)

获取测量模式和尺寸大小

int widthMode = MeasureSpec.getMode(widthMeasureSpec);  //测量模式
int widthSize = MeasureSpec.getSize(widthMeasureSpec);  //尺寸大小

通过widthMeasureSpec拿到宽度尺寸大小并不是最终view的尺寸大小,而是父View提供的参考大小。

测量模式

测量模式表示意思
UNSPECIFIED (未指定模式)就是未指定的意思,在这个模式下父控件不会干涉子View想要多大的尺寸
EXACTLY (精确模式)当前的尺寸就是当前View应该取的尺寸
AT_MOST (最大模式)父组件能够给出的最大的空间,当前组件的长或宽最大只能为这么大,当然也可以比这个小

1.2 动手重写onMeasure函数

需要实现这样一个效果:将当前的View以正方形的形式显示,即要宽高相等,并且默认的宽高值为100像素

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int width = getMyViewSize(100, widthMeasureSpec);
    int height = getMyViewSize(100, heightMeasureSpec);
    if (width < height) {
        height = width;
    } else {
        width = height;
    }
    setMeasuredDimension(width, height);
}


private int getMyViewSize(int defaultSize, int measureSpec) {
    int mySize = defaultSize;
    int mode = MeasureSpec.getMode(measureSpec);
    int size = MeasureSpec.getSize(measureSpec);
    switch (mode) {
        case MeasureSpec.UNSPECIFIED:   //如果没有指定大小,设置为默认大小100
            mySize = defaultSize;
            Log.d(TAG, "getMyViewSize: mode = UNSPECIFIED");
            break;
        case MeasureSpec.EXACTLY:       //如果测量模式是取最大尺寸。可以将大小取最大值,也可以取其他值
            mySize = size;
            Log.d(TAG, "getMyViewSize: mode = EXACTLY");
            break;
        case MeasureSpec.AT_MOST:       //如果是固定的大小,那就不要去改变它
            mySize = size;
            Log.d(TAG, "getMyViewSize: mode = AT_MOST");
            break;
    }
    return mySize;
}

设置布局

<com.android.weather.view.MyView
    android:layout_width="match_parent"
    android:layout_height="100dp"
    android:background="@color/teal_700"/>

效果图
image.png

1.3 重写onDraw

上面已经设置了自定义view尺寸大小,接下来就是把想要的效果画出来吧,直接在画板Canvas对象上绘制。以一个简单的例子去学习:假设我们需要实现的是,让View显示一个圆形,在上面已经实现了宽高尺寸相等的基础上,继续往下做:

@Override
protected void onDraw(Canvas canvas) {
    //调用父View的onDraw函数,因为View这个类实现了一些基本的而绘制功能,比如绘制背景颜色、背景图片等
    super.onDraw(canvas);

    int r = getMeasuredWidth() / 2;     //圆的半径
    //圆心的横坐标为当前的View的左边起始位置+半径
    int centerX = getLeft() + r;
    int centerY = getTop() + r;

    Paint paint = new Paint();
    paint.setColor(Color.RED);

    canvas.drawCircle(centerX, centerY, r, paint);
}

1.4 自定义布局属性

如果有些属性我们希望由用户指定,只有当用户不指定的时候才用我们硬编码的值,比如上面的默认尺寸,我们想要由用户自己在布局文件里面指定该怎么做呢?那当然是通我们自定属性,让用户用我们定义的属性
首先我们需要在res/values/attrs.xml文件(如果没有请自己新建)里面声明一个我们自定义的属性:

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

在布局文件使用自定义的属性 注:需要在根标签设定命名空间 xmlns:app="http://schemas.android.com/apk/res-auto",否则会报错

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <com.android.weather.view.MyView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@color/teal_700"
        app:default_size="200dp"/>

</LinearLayout>

最后在自定义View里面把我们自定义属性的值取出来,在构造函数中,有个AttributeSet参数,需要靠它帮我们把布局里面的属性取出来:

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

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

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

2 自定义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对号入座了,把它们放进它们该放的地方去。
案例:将子View按从上到下垂直顺序一个挨着一个摆放,即模仿实现LinearLayout的垂直布局。

image.png
首先重写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中最大的宽度
            setMeasuredDimension( getMaxViewWidth(), getAllHeight());
        } else if (widthMode == MeasureSpec.AT_MOST) {  //如果只有高度是包裹内容
            //宽度设置为ViewGroup自己的测量宽度,高度设置为所有子View的高度总和
            setMeasuredDimension(widthSize, getAllHeight());
        } else if (heightMode == MeasureSpec.AT_MOST) { //如果只有宽度是包裹内容
            //宽度设置为子View中宽度最大的值,高度设置为ViewGroup自己的测量值
            setMeasuredDimension(getMaxViewWidth(), heightSize);
        }
    }
}

/**
 * 获取子 View 中宽度最大的值
 * @return
 */
private int getMaxViewWidth() {
    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 的高度相加
 * @return
 */
private int getAllHeight() {
    int childCount = getChildCount();
    int height = 0;
    for (int i = 0; i < childCount; i++) {
        View childView = getChildAt(i);
        height = height + childView.getMeasuredHeight();
    }
    return height;
}

上面的onMeasure将子View测量好了,以及把自己的尺寸也设置好了,接下来就是摆放子View

@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
    int viewCount = getChildCount();
    //记录当前的高度位置
    int currentHeight = t;
    //将子View逐个摆放
    for (int i = 0; i < viewCount; i++) {
        View childView = getChildAt(i);
        int childViewWidth = childView.getMeasuredWidth();
        int childViewHeight = childView.getMeasuredHeight();
        //摆放子View,参数分别是子View矩形区域的左、上、右、下边
        childView.layout(l, currentHeight, l + childViewWidth, currentHeight + childViewHeight);
        currentHeight = currentHeight + childViewHeight;
    }
}
<com.android.weather.view.MyViewGroup
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/teal_200">
    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="btn" />
    <Button
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="btn" />
    <Button
        android:layout_width="300dp"
        android:layout_height="wrap_content"
        android:text="btn" />
</com.android.weather.view.MyViewGroup>