Search code examples
androidandroid-fragmentsandroid-viewpagerandroid-tablayout

Contents of fragment remain the same after selecting a new option


Im implementing an Android project where the root navigation is a DrawerLayout. When any of the options is selected in the Drawer, different tabs appear depending on the option selected. I implemented the tabs using this tutorial. However when I select a different option, the title and names of the tabs change but the content is still from the initial tabs that were loaded.

The tabs each have their own fragments. What could I be doing wrong?

Here is a screenshot where I have selected the Registration option and the new tab names are reflecting but the contents are the same:enter image description here

Some of the code from setting up the ViewPager and TabLayout:

    ViewPagerAdapter adapter = new     ViewPagerAdapter((getSupportFragmentManager()));
    //find the elements that will hold the tabs
    viewPager = (ViewPager) findViewById(R.id.viewPager);
    tabLayout = (TabLayout) findViewById(R.id.tabLayout);
    //some switch case statements to add fragments to the adapter here
    //depending on what has been clicked in the nav drawer

    switch (selectedDrawerOption) {
        case R.string.drawer_registration:
            adapter.addFrag(new RegistrationFragment(), AppConst.TAB_PROOF);
            adapter.addFrag(new RegistrationFragment(), AppConst.TAB_STATUS);

            break;
        case R.string.drawer_news:
            adapter.addFrag(new FragmentNews(), AppConst.TAB_CAMPUS);
            adapter.addFrag(new FragmentNews(), AppConst.TAB_SUBJECT);
            break;
}
    viewPager.setAdapter(adapter);
    tabLayout.setupWithViewPager(viewPager);


There is a switch case statement somewhere in between where I fill the adapter.


Solution

  • In this answer it was suggested that the ViewPagerAdapter should extend FragmentStatePagerAdapter and NOT FragmentPagerAdapter and that seems to fix things I can now click another item on the DrawerLayout and the tab names and contents are able to change.