Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ICS + ActionBar Tabs + Orientation change

I managed to make an ActionBar Tab menu, calling different classes who extend Fragments. The problem is, when I change the orientation, switching between menu items does nothing. But I finally figured out the problem.

The main issue here is old fragment don't being removed when orientation changes, so there is always a copy of an unused tab just above user's selected tab

Any ideas? I am missing something basic?

Thank you

like image 842
Eloi Navarro Avatar asked Jan 31 '12 17:01

Eloi Navarro


Video Answer


2 Answers

I finally found the solution by myself, in the onTabSelected method defined in my custom ActionBar.TabListener class I had ft.add that added the fragment to my View.

When the orientation is changed the method onTabUnselected was not called, so the Fragment remained there.

Replacing ft.add to ft.replace managed to erase all old fragments so the new ones where correctly displayed.

Hope this helps someone else

like image 126
Eloi Navarro Avatar answered Sep 27 '22 19:09

Eloi Navarro


I think that's better to save selectedIndex on activity recreation. That way you don't have the problem because the same index is selected and unselected isn't needed and also is nicer for the user.

    protected void onSaveInstanceState(Bundle outState) {   
      super.onSaveInstanceState(outState);
      int i = getActionBar().getSelectedNavigationIndex();
      outState.putInt("selectedTabIndex", i);       
}

    //And then restore
    private void initActionBar(Bundle savedInstanceState) {
        ActionBar ab = getActionBar();
        ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        ab.addTab(...);
            ...

        if(savedInstanceState != null) {
            int index = savedInstanceState.getInt("selectedTabIndex");
            getActionBar().setSelectedNavigationItem(index);
        }   
like image 35
lujop Avatar answered Sep 27 '22 18:09

lujop