自定义View - 2.自定义Textview的onMeasure方法使实战

一般自定义View的步骤:
1.自定义属性
2.实现onMeasure 指定 控件的宽高

onMeasure方法

指定控件的宽高.
说到onMeasure,就不得不说三种测量模式.AT_MOST,EXACTLY,UNSPECIFIED(几乎用不到)

1.对于EXACTLY模式.确定就是说控件已经确定大小了.也就是控件在布局这样写.

ndroid:layout_width="100dp"
//或者
android:layout_width="match_parent"

对于确定控件大小,就不需要计算了.
2.对于AT_MOST模式.不确定大小.就需要自己计算了.对于不同的自定义view.看实际需要计算.就现在自定义Textview的举例.就是文字占的控件多大.就给控件设置宽高为多大.

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        //指定控件的宽高
        //三种测量模式,AT_MOST , EXACTLY,UNSPECIFIED

        //获取测量模式
        int widthMeasureMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMeasureMode = MeasureSpec.getMode(heightMeasureSpec);

        //宽度
        //1,确定的值,不需要计算.给多少就要多少
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);

        //2.wrap_content. 需要计算
        if (widthMeasureMode == MeasureSpec.AT_MOST) {
            //计算宽度 . 宽度和字的长度和字大小有关系 .所以画笔进行测量
            if (mBounds == null) {
                mBounds = new Rect();
            }

            mPaint.getTextBounds(mMyText, 0, mMyText.length(), mBounds);
            widthSize = mBounds.width();
        }


        //高度

        //1,确定的值,不需要计算.给多少就要多少
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        //2.wrap_content. 需要计算
        if (heightMeasureMode == MeasureSpec.AT_MOST) {
            //计算宽度 . 宽度和字的长度和字大小有关系 .所以画笔进行测量
            mPaint.getTextBounds(mMyText, 0, mMyText.length(), mBounds);
            heightSize = mBounds.height();
        }

        setMeasuredDimension(widthSize, heightSize);
    }

我们来看效果.给MyTextview设置背景就可以看到控件的大小

    <com.zsj.mytextview.MyTextView
        android:background="@color/colorAccent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:myText="MyTextView"
        app:myTextColor="@color/colorPrimary"
        app:myTextSize="30sp" />

效果如下.


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容