自定义view(一)----自定义TextView

2022-01-27  本文已影响0人  会写代码的小猿猴

自定义view也算是Android的一大难点,里面涉及到很多值得学习的地方,我会在接下来写一系列文章去介绍它,本篇文章以自定义一个TextView为例。

View的构造方法

自定义view之前我们先了解view的四个构造方法,自定义view无非就是新建一个类去继承View,为了阅读方便,我们采用Java代码进行分析(kotlin语言可读性较差),首先定义一个类TextView2继承View,按照提示实现所有构造方法

public class TextView2 extends View {
    public TextView2(Context context) {
        super(context);
    }

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

    public TextView2(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public TextView2(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }
}

需要实现它的四个构造方法,我在下面分别给出每个构造方法的调用时期。

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

这个构造方法通过阅读源码注释加以理解可以知道,它是在new对象时简单调用的构造方法,其中参数context是视图运行的上下文,通过它可以访问当前的主题、资源等。

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

上面这个构造方法是当TextView2在layout布局中使用时调用,参数:
context-----视图运行的上下文,通过它可以访问当前的主题、资源等
attrs-----使视图膨胀的XML标记的属性

  public TextView2(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

这个构造方法调用时期是在自定义样式时调用,比如我们在layout视图中使用了我们自定义的某个style,就会调用这个构造方法,参数:
context-----视图运行的上下文,通过它可以访问当前的主题、资源等
attrs-----使视图膨胀的XML标记的属性
defStyleAttr-----当前主题中的一个属性,它包含对为视图提供默认值的样式资源的引用

 public TextView2(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

最后这个方法是后面才加入的,也很少用到,它的作用是从XML执行膨胀,并从主题属性或样式资源应用特定于类的基样式。 View的这个构造函数允许子类在膨胀时使用自己的基样式。当确定一个特定属性的最终值时,有四个输入会起作用:

//在第一个构造方法中调用第二个构造方法
    public TextView2(Context context) {
        this(context, null);
    }

    //在第二个构造方法中调用第三个构造方法
    public TextView2(Context context, @Nullable AttributeSet attrs) {

        this(context, attrs, 0);
    }

    //通常在第三个构造方法中获取自定义属性
    public TextView2(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

自定义属性并获取自定义属性

接上文,我们自定义view入门就是自定义一个Textview,系统提供的TextView在布局中使用时基本上如下所示:

   <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="zzp"
        android:textColor="@color/black"
        android:textSize="16sp" />

一个TextView必须具备的就是宽和高的指定,这个在在定义的下一部分会讲,还有就是后面三句,对text、textColor和textSize进行了赋值,这三个就是view的属性,那我们在自定义view时属性也是需要自定义的,那怎么进行属性的自定义呢,我在这里将它分为一下几步

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--自定义属性的名字-->
    <declare-styleable name="TextView2">
        <!--name 属性名称  format 格式-->
       <!-- 常用格式:color  颜色
                    string 文字
                    dimension 宽高或者文字大小
                    reference 资源
                    -->
        <attr name="text1" format="string"/>
        <attr name="textColor1" format="color"/>
        <attr name="textSize1" format="dimension"/>
    </declare-styleable>
</resources>

这没什么好说的,注意看代码中注释的常用格式。现在就是已经自定义了三个属性text1、textColor1、textSize1,分别是string型、color型、dimension型。值得注意的是在自定义属性时系统已经有的属性不能被重复定义,所以name不能用text、textColor和textSize。我都加了个1作区分,不然会被认定为重新定义系统属性而报错。

 <com.example.kotlindemo.TextView2
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:text1="zzp"
        app:textColor1="@color/black"
        app:textSize1="16sp" />

我们使用了自定义的TextView2,并将自定义属性赋值,但是运行还是没有效果,因为我们还需要将自定义的属性与原本的属性相关联,比如自定义的text1属性相当于TextView的text,textColor1属性相当于TextView的textColor等

public class TextView2 extends View {
    private String mText;
    private int mTextColor= Color.BLACK;
    private int mTextSize;
    //在第一个构造方法中调用第二个构造方法
    public TextView2(Context context) {
        this(context, null);
    }

    //在第二个构造方法中调用第三个构造方法
    public TextView2(Context context, @Nullable AttributeSet attrs) {

        this(context, attrs, 0);
    }

    //通常在第三个构造方法中获取自定义属性
    public TextView2(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //获取自定义布局TextView2的属性
        TypedArray array=context.obtainStyledAttributes(attrs,R.styleable.TextView2);
        //将获取到的属性赋值给TextView2的成员变量
        mText=array.getString(R.styleable.TextView2_text1);
        mTextColor=array.getColor(R.styleable.TextView2_textColor1,Color.BLACK);//第二个参数为默认值
        mTextSize=array.getDimensionPixelSize(R.styleable.TextView2_textSize1,18);//注意接收时使用getDimensionPixelSize,在TextView源码中就是使用这个方法接收,也算是个坑
        //回收
        array.recycle();
    }
}

运行起来发现还是没有效果,因为还没有指定宽高和绘画,且往下看。

自定义View中的onMeaSure()

我们在上面实现的代码运行起来依旧一片空白,我也说了是因为没有指定宽高和进行绘画,一步步来,先看指定宽高,怎么指定宽高呢?自定义view时需要在onMeaSure方法为view指定宽高,所以在解决这个问题前我们先来了解一下这个方法的一些基本知识。
onMeaSure()方法是自定义view中一个非常重要的方法,他具体有什么作用呢?它是自定义view的测量方法,view的宽和高都由它来指定。
我们先来看一段代码,了解几样东西。

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //获取宽高的模式
        int widthmode=MeasureSpec.getMode(widthMeasureSpec);
        int heifhtmode=MeasureSpec.getMode(heightMeasureSpec);
    }

在上面这段代码中我们实现了onMeaSure方法,并且在里面获取了两个变量。我们在布局文件中定义view时通常会给view指定宽高,指定宽高时分为三种情况,第一种是包裹内容(wrap_content),第二种是是view充满布局(match_parent),第三种是给view指定一个数值的宽高(比如100dp),上面代码中的

 int widthmode=MeasureSpec.getMode(widthMeasureSpec);
 int heifhtmode=MeasureSpec.getMode(heightMeasureSpec);

可以用来判断该自定义view使用了哪种方式指定宽高,下面我就直接用代码说明获取到的值分别对应哪一种指定宽高的情况。

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //获取宽高的模式
        int widthmode=MeasureSpec.getMode(widthMeasureSpec);
        int heifhtmode=MeasureSpec.getMode(heightMeasureSpec);
        //说明三种情况对应的值,以宽为例
        if (widthmode==MeasureSpec.AT_MOST){
            Log.e("zzp","指定宽度的方式为wrap_content");
        }else if (widthmode==MeasureSpec.EXACTLY){
            Log.e("zzp","指定宽度的方式为确切的值,match_parent,fill_parent");
        }else if (widthmode==MeasureSpec.UNSPECIFIED){
            Log.e("zzp","布局尽可能大,一般在listview,scollview会用到");
        }
    }

如上面代码所示,getMode()能够获取到三个有效值,每个值对应哪种情况,值得注意的是确切值和match_parent都是对应MeasureSpec.EXACTLY,我看到好多博客都把match_parent写成对应MeasureSpec.UNSPECIFIED,这是错误的。
在了解三种测量模式后,我们就可以针对不同情况对view指定宽高,根据三种模式分为三种情况:

public class TextView2 extends View {
    private String mText;
    private int mTextColor = Color.WHITE;
    private int mTextSize;

    private Paint mPaint = new Paint();

    //在第一个构造方法中调用第二个构造方法
    public TextView2(Context context) {
        this(context, null);
    }

    //在第二个构造方法中调用第三个构造方法
    public TextView2(Context context, @Nullable AttributeSet attrs) {

        this(context, attrs, 0);
    }

    //通常在第三个构造方法中获取自定义属性
    public TextView2(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //获取自定义布局TextView2的属性
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.TextView2);
        mText = array.getString(R.styleable.TextView2_text1);
        mTextColor = array.getColor(R.styleable.TextView2_textColor1, Color.BLACK);//第二个参数为默认值
        mTextSize = array.getDimensionPixelSize(R.styleable.TextView2_textSize1, 18);//注意接收时使用getDimensionPixelSize,在TextView源码中就是使用这个方法接收,也算是个坑
        //设置抗锯齿
        mPaint.setAntiAlias(true);
        //设置字体
        mPaint.setTextSize(mTextSize);
        //设置字体颜色
        mPaint.setColor(mTextColor);
        //回收
        array.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //获取宽高的模式
        int widthmode=MeasureSpec.getMode(widthMeasureSpec);
        int heifhtmode=MeasureSpec.getMode(heightMeasureSpec);
        //确切的值,不需要测量
        int width=MeasureSpec.getSize(widthMeasureSpec);
        //给的是wrap_content,需要计算宽高,使用画笔进行计算
        if (widthmode==MeasureSpec.AT_MOST){
            Rect rect=new Rect();
            mPaint.getTextBounds(mText,0,mText.length(),rect);
             width=rect.width();
        }

        int height=MeasureSpec.getSize(heightMeasureSpec);
        if (heifhtmode==MeasureSpec.AT_MOST){
            Rect rect=new Rect();
            mPaint.getTextBounds(mText,0,mText.length(),rect);
            height=rect.width();
        }
        setMeasuredDimension(width,height);
    }
}

为了效果明显,我给了一个黑色背景

<com.example.kotlindemo.TextView2
        android:background="#000"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:text1="zzp"
        app:textColor1="@color/white"
        app:textSize1="16sp" />

现在运行起来就有效果了,有一个黑色的小框,只是没有显示文字,因为还要进行绘画,可以在布局文件中切换wrap_content和确切的值运行后查看效果。关于画笔,有兴趣的同学可以去了解一下,我都是把它当做一个测量的工具,直接死记硬背。

自定义View中的onDraw()

我们在上面实现计算控件宽高,但是显示不出文字,是因为还没进行绘画,所以还需要实现它的onDraw()方法。

 protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //第二个参数--代表开始的水平位置(以控件为基准)
        //第三个参数--基线,baseline
        canvas.drawText(mText,0,getHeight()/2,mPaint);
    }

这样就像是出了效果


image.png

但是发现文字显示偏上,这是因为基线y的值不能直接赋值为高度的一半,这里涉及到多个概念,我也是查阅很多资料才弄懂。

  protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
       //第二个参数--代表开始的水平位置(以控件为基准)
        //第三个参数--基线,baseline
        Paint.FontMetricsInt fontMetricsInt=mPaint.getFontMetricsInt();
        int dy=(fontMetricsInt.bottom-fontMetricsInt.top)/2-fontMetricsInt.bottom;
        int baseLine=getHeight()/2+dy;
        canvas.drawText(mText,0,baseLine,mPaint);
    }

下面借助一张图来解释一下为什么要这样算基线的值


image.png

如果我们想要文字竖直居中,那么基线位置如图中BaseLine一样,先来梳理一下现在的已知条件,
getHeight()/2------整个视图高度的一半
FontMetricsInt.top ----基线到文字顶部的距离,是一个负值
FontMetricsInt.bottom--基线到文字底部的距离,是一个正值
假设基线的值y=getHeight()/2+dy
dy表示基线与高度的一半之间的距离。
dy=(fontMetricsInt.bottom-fontMetricsInt.top)/2-fontMetricsInt.bottom
这样基线的值就可以计算出来了。
重新运行,就能看到竖直居中后的效果了。

上一篇 下一篇

猜你喜欢

热点阅读