migua——day070onWindowsFocusChanged和onPostCreate

来源:互联网 发布:编程待遇 编辑:程序博客网 时间:2024/06/15 08:46

今天偶然间发现了一个貌似很有用处的接口

  1. protected void onPostCreate (Bundle savedInstanceState)
  1. Since: API Level 1

  2. Called when activity start-up is complete (after onStart() and onRestoreInstanceState(Bundle) have been called). Applications will generally not implement this method; it is intended for system classes to do final initialization after application code has run.

  3. Derived classes must call through to the super class's implementation of this method. If they do not, an exception will be thrown.

记得之前想要在Activity布局完成,彻底跑起来之后,再获取当前Activity的窗口中,某个View的宽高,之前用的办法很土,弄个Handler,发个Message出来,使用sendMessageDelayed或者sendEmptyMessageDelayed。
说白了就是延迟若干时间之,等Activity彻底跑起来之后,再取获取View的宽高。
使用这个办法,总是有一种担心:delay的时间太长了,害怕使用这个获取的宽高的值的时候,自己获取宽高的函数还没被调用;delay的时间太短了,又害怕在某些配置比较低的机型上,在delay的时间内Activity没能彻底的跑起来,获取到的值可能会不正确。

从SDK的说明来看,onPostCreate 貌似可以实现我们想要的效果。
系统调用到onPostCreate时,Activity应该已经 start-up (彻底跑起来)了。

onCreate():

Height=0onStart():

Height=0onPostCreate():

Height=0onResume():

Height=0onPostResume():

Height=0onAttachedToWindow(): Height=0onWindowsFocusChanged(): Height=1845可以看到,直到 onWinodwsFocusChanged() 函数被调用,我们才能得到正确的控件尺寸。

其他 Hook 函数,包括在官方文档中,描述为在 Activity 完全启动后才调用的 onPostCreate() 和 onPostResume() 函数,均不能得到正确的结果。 遗憾的是,虽然在 onWinodwsFocusChanged() 函数中,可以得到正确的控件尺寸。但这只在 Activity 中奏效,而在 Fragment 中,该方法并不能生效。


更多的解决方案1.

使用 ViewTreeObserver 提供的 Hook 方法。

@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);   

setContentView(R.layout.activity_welcome);  

myButton = (Button) findViewById(R.id.button1);   

    // 向 ViewTreeObserver 注册方法,以获取控件尺寸    ViewTreeObserver vto = myButton.getViewTreeObserver();    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {  

    public void onGlobalLayout() {           

int h = myButton.getHeight();       

    Log.i(TAG, "Height=" + h); // 得到正确结果             // 成功调用一次后,移除 Hook 方法,防止被反复调用         

  // removeGlobalOnLayoutListener() 方法在 API 16 后不再使用          

// 使用新方法 removeOnGlobalLayoutListener() 代替        

  myButton.getViewTreeObserver().removeGlobalOnLayoutListener(this);        }    });        // ...}

1 0
原创粉丝点击