Search code examples
androidandroid-fragmentsandroid-viewpagerandroid-tablayout

Add fragment to TabLayout on runtime


I've got a TabLayout in my Activity, it shows one fragment when it's created, but I need to be able to add a new fragment to it after completing an operation (or create both when the activity is created, but show only the first, and then show the second).

I've tried adding the fragment to the viewPagerAdapter and then calling the notifyDataSetChanged() method, the frament it's added, but it's title doesn't show up in the tabLayout and if I try to slide to it, I get an IndexOutOfBoundsException: Invalid index 1, size is 1

Does anyone got some advice to give me?

My activity, where I add the first fragmen:

   @Override
   protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.act_one);

   // Crete a new fragment
   FragmentOne fragmentOne = new FragmentoOne();

   tabLayout = (TabLayout) findViewById(R.id.tabLayout);
   viewPager = (ViewPager) findViewById(R.id.viewPager);

   // Creates the viewPagerAdapter
   viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
   
   // Adds the fragment to ViewPagerAdapter
   viewPagerAdapter.addFragment(fragmentoOne, "First"); // this line can cause crashes
   viewPager.setAdapter(viewPagerAdapter);
   tabLayout.setupWithViewPager(viewPager);

}

And here is where I try to add the new fragment:

public void onAddFragment2() {

    viewPagerAdapter.addFragment(new FragmentoTwo(), "Second"); // new FragmentoTwo() should be in FragmentPagerAdapter.getItem()
    viewPagerAdapter.notifyDataSetChanged();

}

Solution

  • set the adapter again after you added it with setAdapter