美文网首页安卓控件
在Android中如何测量View的宽度和高度

在Android中如何测量View的宽度和高度

作者: 秦小怪 | 来源:发表于2017-06-01 16:13 被阅读0次

Android如何测量View的宽度和高度

手动去测量view的宽度和高度在开发时候会经常使用,在此介绍个比较简单的也是很常用的,其他方式暂不讨论,以textview为例

        int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
        textView.measure(widthSpec, heightSpec);
        int measuredHeight = textView.getMeasuredHeight();//测量得到的textview的高
        int measuredWidth = textView.getMeasuredWidth();//测量得到的textview的宽

我们点击View.MeasureSpec.UNSPECIFIED源码会看到值0,在View.MeasureSpec.UNSPECIFIED测量模式下,makeMeasureSpec()后widthSpec和heightSpec都是0

在测量的时候只需要textView.measure(0, 0)就测量可以了

可以简化的写法

        textView.measure(0,0);
        int measuredHeight = textView.getMeasuredHeight();//测量得到的textview的高
        int measuredWidth = textView.getMeasuredWidth();//测量得到的textview的宽

也欢迎大家扫描二维码注我的微信订阅号,Android,java,kotlin,架构等技术讨论,共同进阶为Android高级开发,甚至资深Android开发


秦小怪.jpg

相关文章

网友评论

    本文标题:在Android中如何测量View的宽度和高度

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