Search code examples
androidandroid-tablayoutfragmentstatepageradapter

How to delete a Tab and its associated fragment from TabLayout & FragmentStatePagerAdapter


I am trying to create a program with TabLayout and an option menu which when selected can add or delete the tab along with the fragment. I can delete the tab but I am not able to understand what else needs to be done because I have to delete the fragments that the tab holds, more over I may also have to rearrange the position of the fragments which I just can't seem to figure out. Could you please help me with this ?

under mainAcitivity this is how I add tabs

tabLayout = (TabLayout) findViewById(R.id.tab_layout);

        tab1= tabLayout.newTab().setText("TAB 1");
        tabLayout.addTab(tab1);

        tab2 = tabLayout.newTab().setText("TAB 2");
        tabLayout.addTab(tabKantipur);

This is the FragmentstatePagerAdapter

public class TabPagerAdapter extends FragmentStatePagerAdapter {

    int tabCount;

    public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
        super(fm);
        this.tabCount = numberOfTabs;
    }

    @Override
    public int getItemPosition(Object object) {
        return super.getItemPosition(object);
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
              return NewsFragment.newInstance("data for fragment 1");
            case 1:
               return NewsFragment.newInstance("data for fragment 2");
            default:
                return null;
        }

    }

    @Override
    public int getCount() {
        return tabCount;
    }
}

Basically here NewsFragment is the fragment whose new instance is used in the tabs. Under onActivityResult I am getting the data that has been requested from the options Menu to add or delete fragmetns

 mpagerAdapter = new TabPagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
removedTab = ..data received from ooption menu
// here I want to remove the Tab & the fragments (tab1 & its fragment)


if (removeTab == "tab1") {
  tabLayout.removeTab(tab1);
  mpagerAdapter.notifyDataSetChanged();
}

}

As I do this only the first tab gets removed I would like to know how to remove the associated fragment too.


Solution

  • I had asked a similar question using fragmentarray for which i got it to work . this is the link, Issue: Logic to find the position of a fragment in a fragment arraylist?