如何在Acitivity生命周期里获得View的宽高

如何在Acitivity生命周期里获得View的宽高

原因
无法在Activity的onCreate或者onResume方法中正确的到某个View的宽/高信息,因为View的measure过程和Activity的生命周期方法不是同步执行的,因此无法保证Acitivity执行了onCreate、onStart、onResume时某个View已经测量好了,如果没有测量好,那么获得的宽/高就是0。

解决方法

1、Activity/View.onWindowFocusChanged

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

public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChagned(hasFocus); if(hasFocus){ int width = view.getMeasuredWidth(); int height = view.getMeasuredHeight(); } }

2、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.getMeasuredHeight(); } });}

3、ViewTreeObserver

使用ViewTreeObserver的OnGlobalLayoutListener接口可以实现这个功能。当View树的状态发生改变或者View树内部的View的可见性发生改变时,onGlobalLayout方法将被调用,此时可以获取View的宽高。

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方法获得宽高

你可能感兴趣的:(如何在Acitivity生命周期里获得View的宽高)