ActionBar, Fragment and screen rotation

In the post Tab Layout in Android with ActionBar and Fragment as dnoray wrote in his comment, there is a problem: when you rotate the screen (ctrl + F11 in the emulator) there is an overlap of the two fragments as seen in the figure.

fragment issue

For a further discussion on this topic you can read this.

There are at least three possible solutions, or some variant of these

  • first method
    add a line of code to the file AndroidManifest.xml

    in this way the activity is not destroyed and recreated and you can update the activity by overriding the method onConfigurationChanged() but in this case you don’t need.
    For more information see Handling the Configuration Change Yourself
  • second method
    in the class TabActionBarActivity replace the line 66

    with

    As explained here the method replace is basically a remove + add.
  • third method
    more difficult but interesting

    1. first, you need to know which fragments has been added to the main activity; then you add the following code to the class TabActionBarActivity:

      this code is taken from Is there a way to get references for all currently active fragments in an Activity?
    2. edit the method onTabSelected of the inner class TabListener

One Reply to “ActionBar, Fragment and screen rotation”

  1. Thank you so much, the third method work well and solved my problem.
    But it’s possibile to have the last tab selected after screen rotation?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.