当Activity显示时,将调用哪个生命周期方法?

时间:2012-11-29 05:57:26

标签: android android-activity android-lifecycle

有时我需要在活动刚刚显示时进行一些操作(例如更改布局)。我现在所做的是使用post()

public class MyActivity extends Activity {

     @Override
     public void onCreate() {
         ...
         container.post(new Runnable(){
               resize(container);
         });
     }
}

有没有像onCreate这样的生命周期方法可以用来简化代码,我不需要调用post

@Override
public void onX() {
    resize(container);
}

1 个答案:

答案 0 :(得分:2)

我认为你的意思是在显示用户界面之后做点什么。

使用全局布局侦听器一直很适合我。它具有能够在布局改变时重新测量事物的优点,例如,如果某些内容设置为View.GONE或添加/删除子视图。

public void onCreate(Bundle savedInstanceState)
{
     super.onCreate(savedInstanceState);

     // inflate your main layout here (use RelativeLayout or whatever your root ViewGroup type is
     LinearLayout mainLayout = (LinearLayout ) this.getLayoutInflater().inflate(R.layout.main, null); 

     // set a global layout listener which will be called when the layout pass is completed and the view is drawn
     mainLayout.getViewTreeObserver().addOnGlobalLayoutListener(
     new ViewTreeObserver.OnGlobalLayoutListener() {
          public void onGlobalLayout() {
               // at this point, the UI is fully displayed
          }
     }
 );

 setContentView(mainLayout);

http://developer.android.com/reference/android/view/ViewTreeObserver.OnGlobalLayoutListener.html