Android开发显示之前获取view的宽高方法

记住onCreate、onStart、onResume中均无法正确得到某个View的宽高,因为View的measure过程和Activity的生命周期方法是不同步执行的,如果View还没有测量完毕,那么获得的宽高就是0

1、Activity中的onWindowFocusChanged(),注意被多次调用,可以加标志,获取到想要的就不获取了

@Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(hasFocus){
            int width = rl_head.getMeasuredWidth();
        }
    }
2、view.post(runnable),一般在onCreate中调用,需不需要加延时呢,经过多次验证是不需要加延时的;准确嘛?,98%是准确的

推荐看分析博客http://blog.csdn.net/scnuxisan225/article/details/49815269

ivHead.post(new Runnable() {
            @Override
            public void run() {
                int width = ivHead.getMeasuredWidth();

            }
        });
3、ViewTreeObserver(),注意被多次调用

 ViewTreeObserver vto = holder.ll_looked.getViewTreeObserver();
            vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    holder.ll_looked.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    LogUtils.i("ll_look_height",holder.ll_looked.getHeight()+"");

                 
                }
            });
4、view.measure,不推荐使用

总结考虑使用顺序2314,总的归结思考的方向view的宽高是在measure,layout后才确定的

所有试过才知道的,获取宽高不同环境下可能不一样或者不行




你可能感兴趣的:(android开发日记)