Android - Programmatically Creating Views

If, like me, you think XML is a load of over-complicated cow poo and prefer to create your views programmatically in the "onCreate" function then there's one thing you should keep in mind. By default, the "onSaveInstanceState" function will save any view with an Id into a "savedInstanceBundle". These "saved" views will then be recreated if one calls the customary base class "onCreate" function and passes it the previously saved "savedInstanceBundle". For example...


  @Override
  public void onCreate(android.os.Bundle savedInstanceState) 
  {
    super.onCreate(savedInstanceState); // <--- will recreate views

    // your code to programmatically create all required views...
  }

This can be less than ideal and unnecessary if you already have all the code to build these views in the "onCreate" function. This can also cause issues for other threads or simply complicate things if you need to keep track of instantiated classes.

My solution was to just call the base class "onCreate" function and pass a null so no views are created. An alternative might also be to override the "onSaveInstanceState" function to not save any views.


Popular Posts