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.
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
1android:configChanges=”orientation|screenSize”
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
1ft.add(android.R.id.content, mFragment, mTag);
with
1ft.replace(android.R.id.content, mFragment, mTag);
As explained here the method replace is basically a remove + add. - third method
more difficult but interesting- first, you need to know which fragments has been added to the main activity; then you add the following code to the class TabActionBarActivity:
1234567891011121314151617List<WeakReference<Fragment>> fragList = new ArrayList<WeakReference<Fragment>>();@Overridepublic void onAttachFragment(Fragment fragment) {fragList.add(new WeakReference(fragment));}public ArrayList<Fragment> getActiveFragments() {ArrayList<Fragment> ret = new ArrayList<Fragment>();for (WeakReference<Fragment> ref : fragList) {Fragment f = ref.get();if (f != null && f.isVisible()) {ret.add(f);}}return ret;}
this code is taken from Is there a way to get references for all currently active fragments in an Activity? - edit the method onTabSelected of the inner class TabListener
1234567891011121314151617181920212223242526272829public void onTabSelected(Tab tab, FragmentTransaction ft) {Iterator<WeakReference<Fragment>> it = fragList.iterator();while (it.hasNext()) {Fragment f = it.next().get();if (f.getTag().equals(mTag)) {if (f instanceof Tab1Fragment) {mFragment = (Tab1Fragment) f;} else if (f instanceof Tab2Fragment) {mFragment = (Tab2Fragment) f;} else {mFragment = f;}} else {ft.detach(f);}}// Check if the fragment is already initializedif (mFragment == null) {// If not, instantiate and add it to the activitymFragment = Fragment.instantiate(mActivity, mClass.getName());ft.add(android.R.id.content, mFragment, mTag);} else {// If it exists, simply attach it in order to show itft.attach(mFragment);}}
- first, you need to know which fragments has been added to the main activity; then you add the following code to the class TabActionBarActivity:
One reply on “ActionBar, Fragment and screen rotation”
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?