2012-04-06

Get layout values in onCreate method. And Speed up Activity loading times.

Activity#onCreate() is the one of most fundamental methods in Android app creation. However there are some difficulties for this method. For example, you can't obtain layout values of views because layout values are not fixed until the codes in onCreate() methods is done.

But few hacks are left to get layout values in the methods.

The hack is to use IdleHandler (see the IdleHandler description in Android SDK's page). With using IdleHandler, you can run your code after the Android systems finish running current tasks which the UI thread holds.

This hack is also useful to speed up activity loading times, because tasks defined in IdleHandler would be processed after the screen is displayed.

@Override
  public void onCreate(Bundble savedInstanceState)
  {
    super.onCreate(savedInstanceState);

    ...


    Looper.myQueue().addIdleHandler(new MessageQueue.IdleHandler()
      {
        @Override
        public boolean queueIdle()
        {
          HEIGHT_OF_MENU_RELATIVE_LAYOUT = findViewById(R.id.main_rlMenu).getHeight();
          return false;
        }
      }
    );
  }
      

No comments:

Post a Comment