美文网首页
自定义控件

自定义控件

作者: _戏_梦 | 来源:发表于2022-04-28 17:34 被阅读0次

    自定义控件

    在开发中,开发者常常会因为下面四个主要原因去自定义 View:

    1. 让界面有特定的显示风格、效果;
    2. 让控件具有特殊的交互方式;
    3. 优化布局;
    4. 封装;

    1让界面有特定的显示风格、效果

    在开发中,Android SDK提供了很多控件,但有时,这些控件并不能满足业务需求。例如,想要用一个折线图来展示一组数据,这时如果用系统提供的 View 就不能实现了,只能通过自定义 View 来实现。

    2 让控件具有特殊的交互方式

    Android SDK提供的控件都有属于它们自己的特定的交互方式,但有时,控件的默认交互方式并不能满足业务的需求。例如,开发者想要缩放 ImageView 中的图片内容,这时如果用系统提供的 ImageView 就不能实现了,只能通过自定义 ImageView 来实现。

    3 优化布局

    有时,有些布局如果用系统提供的控件实现起来相当复杂,需要各种嵌套,虽然最终也能实现了想要的效果,但性能极差,此时就可以通过自定义 View 来减少嵌套层级、优化布局。

    4 封装

    有些控件可能在多个地方使用,如大多数 App 里面的底部 Tab,顶部的标题栏,像这样的经常被用到的控件就可以通过自定义 View 将它们封装起来,以便在多个地方使用。

    自定义ViewGroup

    以TopBar为例,讲解如何自定义ViewGroup来实现封装的目的。可以使用xml文件,也可以全部使用Java代码。

    简单案例实现

    首先说明这个TopBar的功能。TopBar是作为放在屏幕最上方的标题栏使用的。最主要的功能有两个,一个是左侧的返回按钮,一个是中心的文本,显示当前界面的标题。右侧的功能按钮或文字在不同的界面有不同的样式,所以这里不管。

    布局文件代码

    下面就是对应的布局文件的代码,

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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="48dp"
        android:background="@color/white"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">
    
        <ImageView
            android:id="@+id/btn_back"
            android:layout_width="34dp"
            android:layout_height="28dp"
            android:layout_marginStart="5dp"
            android:background="?attr/selectableItemBackgroundBorderless"
            android:padding="5dp"
            android:src="@drawable/ic_back_nav"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <TextView
            android:id="@+id/tv_title"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="80dp"
            android:layout_marginEnd="80dp"
            android:gravity="center"
            android:lines="1"
            android:textColor="@color/text_333333"
            android:textSize="18sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            tools:text="标题" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    下面就是简单的对应的Java代码。

    构造方法的详细说明见下面的小节,这里只要覆写前两个构造方法即可。

    public class TopBar extends ConstraintLayout {
    
        private ImageView mIvBack;
    
        public TopBar(@NonNull Context context) {
            this(context, null);
        }
    
        public TopBar(@NonNull Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
            // 这行代码的意思就是加载layout_top_bar这个xml布局文件到TopBar这个对象中。
            // 就是将xml代码与这个实例建立联系。
            LayoutInflater.from(context).inflate(R.layout.layout_top_bar, this);
            // init方法是进行一些初始化操作
            init(attrs);
        }
    
        /**
         * 一般都会有的方法,进行初始化操作
         *
         * @param attrs 初始时可能用到的参数,可以用来调用一些系统的方法
         */
        private void init(AttributeSet attrs) {
            // 统一处理设置左上角按钮的返回点击事件,如果是Activity,就调用onBackPressed方法
            mIvBack = findViewById(R.id.btn_back);
            mIvBack.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Context context = getContext();
                    if (context instanceof Activity) {
                        ((Activity) context).onBackPressed();
                    }
                }
            });
        }
    }
    

    到目前为止,这个TopBar其实只有一个功能,就是点击了返回按钮,能够返回上一个界面。

    如何使用

    和我们以前使用其他控件一样使用就好,比如我想让这个标题栏,放在某个界面的上面,直接在xml文件中使用即可。

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout 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=".module.animation.TweenActivity">
    
        <cn.com.fkw.test.view.TopBar
            android:id="@+id/top_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
        
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    在xml中的预览效果:

    标题栏效果

    到这里我们会发现一个问题,就是标题栏的标题的文本似乎无法更改。

    自定义属性

    其实就这样使用,强行通过view.findViewById()的方式,也能修改自定义内部的控件的属性,但是不方便。我么可以通过自定义属性的形式来更加方便的定制我们自己想要的属性。

    比如我想在TopBar中添加一个叫centerText的属性,来指定中间TextView显示的文字。

    实现方式

    1. 在values目录下新建arrts.xml文件。添加成为如下的代码
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    
        <!-- 首先哪个类要自定义属性 -->
        <declare-styleable name="TopBar">
            <!-- 内部是一个个标签,name是写在布局文件中的控件的属性的名字 format是属性值的格式 -->
            <!-- 这个意思就是TopBar可以有一个叫centerText的属性,值是字符串或者字符串引用 -->
            <attr name="centerText" format="string" />
        </declare-styleable>
    
    </resources>
    
    1. 在init方法中获取属性值,然后设置进TextView中
            // 通过attrs获取xml中写的属性值。这里只有centerText一个属性
            TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.TopBar);
            String centerText = typedArray.getString(R.styleable.TopBar_centerText);
            // 这里必须调用typedArray.recycle()方法
            typedArray.recycle();
            
            // 然后将属性设置给TextView
            TextView tv_title = findViewById(R.id.tv_title);
            tv_title.setText(centerText);
    
    1. 使用。

      在布局文件中,使用对应的属性。这样运行之后,我们就能看到标题栏的文字是微信两个字了

    <cn.com.fkw.test.view.TopBar
        android:id="@+id/top_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:centerText="微信"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    

    详细解释

    1. attrs.xml文件

    在这个文件中都是自定义属性相关的内容。格式和案例一样就行。需要额外说明的是format的种类。

    format 类型 说明
    string 字符串
    integer 整数
    float 小数
    color 颜色
    boolean 布尔值
    dimension 尺寸
    enum 枚举 在几个选项中选择一个
    reference 参考的某一资源ID
    flag 位或运算 在几个选项中选择多个
    fraction 百分数

    位或运算

    <!-- 声明 -->
    <attr name="gravity">
        <flag name="top" value="0x30" />
        <flag name="bottom" value="0x50" />
        <flag name="left" value="0x03" />
        <flag name="right" value="0x05" />
        <flag name="center_vertical" value="0x10" />
    </attr>
    
    <!-- 使用 -->
    <TextView android:gravity="bottom|left"/>
    

    通过代码设置属性

    在init方法中,findViewById找到控件,将控件设置为成员变量,然后提供一些应有的方法即可。

    View的构造方法

    一共有4个,我们一般情况下会复写前两个构造方法,且互相调用

    /**
     * 一般情况下我们都是覆写 前两个构造方法
     */
    public class CircleView extends View {
        /**
         * 在Java中创建一个新的CircleView对象时使用。
         * 如果你需要在Java中新建这个View,必须覆写这个构造方法
         *
         * @param context
         */
        public CircleView(Context context) {
            // 这里直接调用参数较多的方法,保证自定义View的某些初始化动作一定执行
            this(context, null);
        }
    
        /**
         * 在xml中添加的控件,被渲染成View时,会调用这个方法。
         * 所以如果想要在xml中使用这个控件,这个构造方法必须复写。
         *
         * @param context
         * @param attrs   如果有自定义的属性,需要用到这个参数
         */
        public CircleView(Context context, @Nullable AttributeSet attrs) {
            super(context, attrs);
        }
    
        /**
         * 与主题相关,如果你不需要当前的View随主题的变化而有更改,就不需要复写这个构造方法。
         */
        public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        /**
         * 与主题相关,如果你不需要当前的View随主题的变化而有更改,就不需要复写这个构造方法。
         */
        public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    }
    

    自定义View

    用一个最简单的案例演示如何继承View,实现自定义View。

    画一个圆

    Android的View的绘制流程

    我们一般需要处理三个方法。View显示在屏幕上,也是经历三个过程,测量、布局和绘制。

    测量:onMeasure

    在 View 的测量阶段会执行两个方法(在测量阶段,View 的父 View 会通过调用 View 的 measure() 方法将父 View 对 View 尺寸要求传进来。紧接着 View 的 measure() 方法会做一些前置和优化工作,然后调用 View 的 onMeasure() 方法,并通过 onMeasure() 方法将父 View 对 View 的尺寸要求传入。在自定义 View 中,只有需要修改 View 的尺寸的时候才需要重写 onMeasure() 方法。在 onMeasure() 方法中根据业务需求进行相应的逻辑处理,并在最后通过调用 setMeasuredDimension() 方法告知父 View 自己的期望尺寸)。

    onMeasure() 计算 View 期望尺寸方法如下:

    1. 参考父 View 的对 View 的尺寸要求和实际业务需求计算出 View 的期望尺寸:
    • 解析 widthMeasureSpec;
    • 解析 heightMeasureSpec;
    • 将「根据实际业务需求计算出 View 的尺寸」根据「父 View 的对 View 的尺寸要求」进行相应的>修正得出 View 的期望尺寸(通过调用 resolveSize() 方法);
    1. 通过 setMeasuredDimension() 保存 View 的期望尺寸(实际上是通过 setMeasuredDimension() 告知父 View 自己的期望尺寸);

    具体的测量过程很复杂。不再赘述。想要了解,请看Android自定义View的测量过程详解。我们需要了解的知识有下面这些:

    MeasureSpec,有人叫它测量规格,我更喜欢把它描述成为测量过程中必不可少的工具——尺子。
    这个尺子有两种用法,横着用就叫做widthMeasureSpec,用来测量宽度,竖着用就叫做heightMeasureSpec,用来测量高度的,不管你的自定义View是什么千奇百怪的形状,他都是要放在一个矩形中进行包裹展示的,那么为什么会有这两个测量方式也就不难理解了。
    这个尺子有两个重要的功能,第一个功能自然是测量值了(Size),第二个功能是测量的模式(Mode),这两个参数通过二进制将其打包成一个int(32位)值来减少对内存的分配,其高2位(31,32位)存放的是测量模式,而低30位则存储的是其测量值。

    测量模式(specMode)

    测量模式分为三种:

    • UNSPECIFIED模式:本质就是不限制模式,父视图不对子View进行任何约束,View想要多大要多大,想要多长要多长,这个在我们写自定义View中的时候非常少见,一般都是系统内部在设置ListView或者是ScrollView的时候才会用到。
    • EXACTLY模式:该模式其实对应的场景就是match_parent或者是一个具体的数据(50dp或80px),父视图为子View指定一个确切的大小,无论子View的值设置多大,都不能超出父视图的范围。
    • AT_MOST模式:这个模式对应的场景就是wrap_content,其内容就是父视图给子View设置一个最大尺寸,子View只要不超过这个尺寸即可。
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        
        // 获取宽
        // 方式一:
        int width1 = MeasureSpec.getSize(widthMeasureSpec);
        // 方式二:
        int width2 = getMeasuredWidth();
    
        // 获取宽
        // 方式一:
        int height1 = MeasureSpec.getSize(heightMeasureSpec);
        // 方式二:
        int height2 = getMeasuredHeight();
        
        // 上面补充自己的逻辑,更改控件的宽高,最后记得调用 setMeasuredDimension 将测量的宽高设置回去
        setMeasuredDimension(100,100);
    }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int width = resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec);
            int height = resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec);
            setMeasuredDimension(width, height);
        }
    
    
        public static int resolveSize(int size, int measureSpec) {
            int result = size;
    
            int specMode = MeasureSpec.getMode(measureSpec);
            int specSize = MeasureSpec.getSize(measureSpec);
    
            switch (specMode) {
                case MeasureSpec.UNSPECIFIED:
                    result = size;
                    break;
                case MeasureSpec.AT_MOST:
                case MeasureSpec.EXACTLY:
                    result = specSize;
                    break;
            }
            return result;
    
        }
    

    布局:onLayout

    layout() : 保存 View 的实际尺寸。调用 setFrame() 方法保存 View 的实际尺寸,调用 onSizeChanged() 通知开发者 View 的尺寸更改了,并最终会调用 onLayout() 方法让子 View 布局(如果有子 View 的话。因为自定义 View 中没有子 View,所以自定义 View 的 onLayout() 方法是一个空实现);

    onLayout() : 空实现,什么也不做,因为它没有子 View。如果是 ViewGroup 的话,在 onLayout() 方法中需要调用子 View 的 layout() 方法,将子 View 的实际尺寸传给它们,让子 View 保存自己的实际尺寸。因此,在自定义 View 中,不需重写此方法,在自定义 ViewGroup 中,需重写此方法。

    绘制:onDraw

    在 View 的绘制阶段会执行一个方法——draw(),draw() 是绘制阶段的总调度方法,在其中会调用绘制背景的方法 drawBackground()、绘制主体的方法 onDraw()、绘制子 View 的方法 dispatchDraw() 和 绘制前景的方法 onDrawForeground():

    • draw()

    draw() : 绘制阶段的总调度方法,在其中会调用绘制背景的方法 drawBackground()、绘制主体的方法 onDraw()、绘制子 View 的方法 dispatchDraw() 和 绘制前景的方法 onDrawForeground();

    drawBackground() : 绘制背景的方法,不能重写,只能通过 xml 布局文件或者 setBackground() 来设置或修改背景;

    onDraw() : 绘制 View 主体内容的方法,通常情况下,在自定义 View 的时候,只用实现该方法即可;

    dispatchDraw() : 绘制子 View 的方法。同 onLayout() 方法一样,在自定义 View 中它是空实现,什么也不做。但在自定义 ViewGroup 中,它会调用 ViewGroup.drawChild() 方法,在 ViewGroup.drawChild() 方法中又会调用每一个子 View 的 View.draw() 让子 View 进行自我绘制;

    onDrawForeground() : 绘制 View 前景的方法,也就是说,想要在主体内容之上绘制东西的时候就可以在该方法中实现。

    注意:
    Android 里面的绘制都是按顺序的,先绘制的内容会被后绘制的盖住。

    Paint和Canvas

    参考资料

    android 自定义属性

    android 自定义属性值类型的详解

    Android自定义View|温故而知新

    Android自定义View的测量过程详解

    详解安卓MeasureSpec及其和match_parent、wrap_content的关系

    match_parent、wrap_parent、具体值 和 MeasureSpec 类中 mode 的对应关系

    Android BitmapShader 实战 实现圆形、圆角图片——hongyang

    相关文章

      网友评论

          本文标题:自定义控件

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