2012-11-29 53 views
0

有时我需要在活动刚刚显示时进行一些操作(例如更改布局)。我现在要做的是使用post()活动显示时将调用哪个生命周期方法?

public class MyActivity extends Activity { 

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

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

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

你的意思是在手术后完全显示的UI? – Simon

+2

Android的罗曼盖伊在[在所有视图完全绘制后触发了什么事件?](http://stackoverflow.com/q/3947145/1267661)中描述了类似这样的方法。所以不行。处理程序是你最好的选择。 – Sam

+0

您可以阅读http://stackoverflow.com/questions/6812003/difference-between-oncreate-and-onstart – logcat

回答

2

我认为你的意思是在UI显示后做些事情。

使用全局布局侦听器对我来说一直效果不错。它具有能够在布局改变时重新测量事物的优点,例如,如果某项设置为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

相关问题