View工作原理 -- 工作过程 -- measure(3)

获取View的宽/高

在Activity的onCreate、onStart、onResume中均无法正确得到某个View的宽/高信息,这是因为View的measure过程和Activity的生命周期方法不是同步执行的,因此无法保证Activity执行了onCreate、onStart、onResume时某个View已经测量完毕了,如果View还没有测量完毕,那么获得的宽/高就是0。可以通过以下几种方法获取。

一、Activity/View#onWindowFocusChanged

onWindowFocusChanged方法的含义是:View已经初始化完毕,宽/高已经准备好了,这个时候去获取宽/高是没问题的。需要注意的是,当Activity的窗口得到焦点和失去焦点时均会被调用一次。

pubic void onWinowFocusChanged(boolean hasFocus) {
    super.onWinowFocusChanged(hasFocus);
    if(hasFocus) {
        int widht = view.getMeasuredWidth();
        int height = view.getMeasuredHeight();
    }
}

二、view.post(runnable)

通过post可以将runnable投递到消息队列的尾部,然后等待Looper调用此runnable的时候,View也已经初始化好了。

protected void onStart() {
    super.onStart();
    view.post(new Runnable() {
        @Override
        public void run() {
            int width = view.getMeasuredWidth();
            int height = view.getMeasureHeight();
        }
    });
}

三、ViewTreeObserver

使用ViewTreeObserver的众多回调可以完成这个功能,比如使用OnGlobalLayoutListener接口,当View树的状态发生改变或者View树内部的View的可见性发生改变时,onGlobalLayout方法将被回调。需要注意的是,伴随着View树的状态改变等,onGlobalLayout方法会被回调多次。

protected void onStart() {
    super.onStart();
    ViewTreeObserver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
        @SuppressWarnings("deprecation")
        @Override
        public void onGlobalLayout() {
            view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
        }
    });
}

四、view.measure(int widthMeasureSpec, int heightMeasureSpec)

通过手动对View进行measure来得到View的宽/高。这种情况比较复杂,需要分情况处理,根据View的LayoutParams来分:
1.match_parent
无法measure出具体的宽/高。原因很简单,根据View的measure过程,构造此种MeasureSpec需要知道parentSize,即父容器的剩余空间,而这个时候我们无法知道parentSize,所以理论上不可能测量出View的大小。
2.固定大小
比如宽/高都是100px,代码如下:

int widthMeasureSpec = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
view.measure(widthMeasureSpec, heightMeasureSpec);

3.wrap_content
代码如下:

int widthMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
view.measure(widthMeasureSpec, heightMeasureSpec);

在最大化模式下,用View理论上能支持的最大值去构造MeasureSpec是合理的。
例子:

//布局



    

    

你可能感兴趣的:(View工作原理 -- 工作过程 -- measure(3))