0

Sometimes I need to do some operations(e.g. changing layout) when the activity is just showing. What I do now is using post():

public class MyActivity extends Activity {

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

Is there any lifecycle method like onCreate can be used to simplify the code, that I don't need to call post?

@Override
public void onX() {
    resize(container);
}
Freewind
  • 193,756
  • 157
  • 432
  • 708
  • Do you mean an operation after the UI is fully displayed? – Simon Nov 29 '12 at 06:00
  • 2
    Android's Romain Guy wrote about methods like this in [What event is fired after all views are fully drawn?](http://stackoverflow.com/q/3947145/1267661). So, no. The Handler is your best bet. – Sam Nov 29 '12 at 06:03
  • You can read http://stackoverflow.com/questions/6812003/difference-between-oncreate-and-onstart – logcat Nov 29 '12 at 07:17

1 Answers1

2

I think you mean do something after the UI is displayed.

Using a global layout listener has always worked well for me. It has the advantage of being able to remeasure things if the layout is changed, e.g. if something is set to View.GONE or child views are added/removed.

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

Simon
  • 14,407
  • 8
  • 46
  • 61