美文网首页Android之旅Android 基础
Android 基础之自定义 View

Android 基础之自定义 View

作者: Kevin_小飞象 | 来源:发表于2019-02-11 15:18 被阅读39次

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

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

    1. onMeasure()

    自定义 View,首先要测量宽高尺寸。在学习 Android 的时候,我们就知道,在 xml 布局文件中,我们的 layout_width 和 layout_height 参数可以不用写具体的尺寸,而是 wrap_content 或者是 match_parent 。其意思我们都知道,就是将尺寸设置为“包住内容”和“填充父布局给我们的所有空间”。这两个设置并没有指定真正的大小,可是我们绘制到屏幕上的 View 必须是要有具体的宽高的,正是因为这个原因,我们必须自己去处理和设置尺寸。当然了,View 类给了默认的处理,但是如果 View 类的默认处理不满足我们的要求,我们就得重写 onMeasure() 函数啦。
    onMeasure() 函数原型:

    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 存放的是尺寸的数据。
    注意:这里的尺寸大小并不是最终我们的 View 的尺寸大小,而是父View提供的参考大小。

    • UNSPECIFIED 表示父容器没有对当前View有任何限制,当前View可以任意取尺寸;
    • EXACTLY 表示当前的尺寸就是当前View应该取的尺寸
    • AT_MOST 表示当前尺寸是当前View能取的最大尺寸

    1.1 动手写 onMeasure()

    需求:将当前的View以正方形的形式显示,即要宽高相等,并且默认的宽高值为100像素。
    MyView.java

    package com.scarf.demo007;
    
    import android.content.Context;
    import android.support.annotation.Nullable;
    import android.util.AttributeSet;
    import android.view.View;
    
    /**
     * Created on 2019/2/11 14:36
     *
     * @author Scarf Gong
     */
    public class MyView extends View {
        public MyView(Context context) {
            super(context);
        }
    
        public MyView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
        }
    
        @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);
        }
    
        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;
        }
    }
    
    

    设置一下布局 activty_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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:gravity="center"
        tools:context=".MainActivity">
    
        <com.scarf.demo007.MyView
            android:layout_width="wrap_content"
            android:layout_height="100dp"
            android:background="@color/colorAccent"/>
    
    </LinearLayout>
    
    效果图

    1.3 动手写 onDraw()

    需求:在以上基础上实现一个圆形。
    MyView.java

    @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.YELLOW);
            //开始绘制
            canvas.drawCircle(centerX, centerY, r, paint);
        }
    

    布局文件:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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"
    tools:context=".MainActivity">
    
    <com.scarf.demo007.MyView
        android:layout_width="wrap_content"
        android:layout_height="100dp"/>
    
    </LinearLayout>
    
    效果图

    1.4 自定义布局属性

    首先我们需要在 res/values/attrs.xml 文件里面声明一个我们自定义的属性:

    <?xml version="1.0" encoding="utf-8"?>
    <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: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"
    tools:context=".MainActivity">
    
    <com.scarf.demo007.MyView
        android:layout_width="wrap_content"
        android:layout_height="100dp"
        app:default_size="100dp"/>
    
    </LinearLayout>
    

    注意:需要在根标签(LinearLayout)里面设定命名空间,命名空间名称可以随便取,比如app,命名空间后面取得值是固定的:"http://schemas.android.com/apk/res-auto"

    最后就是在我们的MyView的构造函数里面把我们自定义的属性的值取出来:

        private int defalutSize;
        public MyView(Context context) {
            super(context);
        }
    
        public MyView(Context context, @Nullable 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.java 完整代码:

    package com.scarf.demo007;
    
    import android.content.Context;
    import android.content.res.TypedArray;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.support.annotation.Nullable;
    import android.util.AttributeSet;
    import android.view.View;
    
    /**
     * Created on 2019/2/11 14:36
     *
     * @author Scarf Gong
     */
    public class MyView extends View {
        private int defalutSize;
        public MyView(Context context) {
            super(context);
        }
    
        public MyView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView);
            defalutSize = a.getDimensionPixelSize(R.styleable.MyView_default_size, 100);
            a.recycle();
        }
    
        @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);
        }
    
        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: {
                    mySize = size;
                    break;
                }
                case MeasureSpec.EXACTLY: {
                    mySize = size;
                    break;
                }
            }
            return mySize;
        }
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
            int r = getMeasuredWidth() / 2;
            int centerX = getLeft() + r;
            int centerY = getTop() + r;
    
            Paint paint = new Paint();
            paint.setColor(Color.YELLOW);
            canvas.drawCircle(centerX, centerY, r, paint);
    
    
        }
    
    }
    
    

    相关文章

      网友评论

        本文标题:Android 基础之自定义 View

        本文链接:https://www.haomeiwen.com/subject/mprqeqtx.html