Abhishek Bhatt
Abhishek Bhatt

Reputation: 3

Android Fragment create duplicate tabs every time when I come back to same fragment

I have create the sample activity using frame layout and fragment with tabs. However, when I switch to other activity/fragment and than comes back to same activity/fragment, it always create duplicate entry or view for tabs. for example, I have tab1 and tab2, when I view activity for first time it display two tabs, but when i switch to other activity and comes back to tabs activity it display four tabs, 'tab1, tab2, tab1, tab2'.

This is my code

public View onCreateView(LayoutInflater Inflater, ViewGroup Container,Bundle savedInstanceState) {

    if(savedInstanceState==null) {
        rootView = Inflater.inflate(R.layout.loanapplicationview, Container, false);

        actionBar = getActivity().getActionBar();

        // Hide Actionbar Icon
        actionBar.setDisplayShowHomeEnabled(true);

        // Hide Actionbar Title
        actionBar.setDisplayShowTitleEnabled(true);

        // Create Actionbar Tabs
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Set Tab Icon and Titles
        Tab1 = actionBar.newTab().setText("Tab1");
        Tab2 = actionBar.newTab().setText("Tab2");


        // Set Tab Listeners
        Tab1.setTabListener(new TabListener(fragmentTab1));
        Tab2.setTabListener(new TabListener(fragmentTab2));


        // Add tabs to actionbar
        actionBar.addTab(Tab1);
        actionBar.addTab(Tab2);

    }
    return rootView;
  }
 }

Upvotes: 0

Views: 1220

Answers (2)

Dreagen
Dreagen

Reputation: 1743

You should check if the tabs exist before adding them.

if (actionBar.getTabCount() == 0) {
    // Set Tab Icon and Titles
    Tab1 = actionBar.newTab().setText("Tab1");
    Tab2 = actionBar.newTab().setText("Tab2");

    // Set Tab Listeners
    Tab1.setTabListener(new TabListener(fragmentTab1));
    Tab2.setTabListener(new TabListener(fragmentTab2));

    actionBar.addTab(Tab1);
    actionBar.addTab(Tab2);
}

Upvotes: 1

SathMK
SathMK

Reputation: 1171

ActionBar().removeAllTabs() will remove all the tabs attached to your ActionBar. So before addinf new tabs clear the previous ones with this method

   actionBar.removeAllTabs();

// Add tabs to actionbar
    actionBar.addTab(Tab1);
    actionBar.addTab(Tab2);

Upvotes: 0

Related Questions