本文主要是介绍getWidth和getMeausuredWidth的区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一直疑惑为什么有个getWidth还要有个getMeasuredWidth方法,以为两者是一样的,实际中好像大多数情况确实是一样的。今天研究View.offsetLeftAndRight函数以及View.getLeft函数,稍微看了下源码,貌似知道了两者的区别.
- getMeasuredWidth是onMeasure阶段根据view的布局参数以及其padding等各种属性计算出来的,由View.setMeasuredDimension(int width,int height)函数的第一个参数width决定,getMeasuredWidth返回的就是View的一个成员变量mMeasuredWidth而已。
//getMeasuredWidth源码public final int getMeasuredWidth() {return mMeasuredWidth & MEASURED_SIZE_MASK;}
- getWidth返回的其实就是view的mRight属性减去mLeft属性的差值,mLeft和mRight以及mTop,mBotton表示view在其父控制中的位置(以父控件左上角为原点),而这四个值是由public void layout(int l, int t, int r, int b)的四个参数决定的。 实际中为什么两者(getWidth和getMeasuredWidth)结果大多数是一样的呢?因为view.layout(int l, int t, int r, int b)传入的四个参数一般都是这样的,left, top, left + getMeasuredWidth, top + getMeasuredHeight, 这样的话,getWidth = mRight - mLeft刚好等于getMeasuredWidth了
//getWidth源码public final int getWidth() {return mRight - mLeft;}
总结一下,getMeasuredWidth是在measure阶段由View.setMeasuredDimension(int width,int height)函数的第一个参数width决定; getWidth是在layout阶段由mRight - mLeft决定,在代码中通过View.setLeft, View.setRight可以改变getWidth大小,可以改变其可见区域
这篇关于getWidth和getMeausuredWidth的区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!