Dynamically updating TabLayout without changing selected tab
Asked Answered
E

2

10

I want to implement a wizard with Material Design Support library.

I'm using ViewPager and Tablayout but I have a problem adding new tabs dynamically.

First, I set up my widgets in onCreate method:

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

adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new DummyFragment(), "1");
adapter.addFrag(new DummyFragment(), "2");
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);

Then I want to add another card, when an element in the list is clicked:

adapter.addFrag(new DummyFragment(), "3");
adapter.notifyDataSetChanged();
tabLayout.setTabsFromPagerAdapter(adapter);

The problem is: after adding, selected card was resets to first.

How to prevent this behaviour?

Entomostracan answered 16/12, 2015 at 20:19 Comment(0)
C
1

This is a slight modification to @Kalpit code. You will have to dynamically add this new tab to our layout and assign the title by calling the same method from adapter which is called by tablayout when you use setupWithViewPager method.So i used this try catch statement for tabs which have not yet been created yet but you might try to assign them some title.

    adapter.notifyDataSetChanged();
    for(int i = 0;i<adapter.getCount();i++){
      try{
        tablayout.getTabAt(i).setText(adapter.getPageTitle(i));
      }
      catch(IndexOutOfBoundException e){
        tablayout.addTab(tablayout.newTab().setText(adapter.getPageTitle(i));
      }
    }
Coleslaw answered 12/5, 2016 at 10:34 Comment(0)
O
0

Just ran in the same problem, and luckily found a solution (not a pretty one, but it works):

when you need to update tabs:

pageradapter.notifyDataSetChanged();
for (int i = 0; i < viewpager.getCount(); i++) {
    sectionsTabLayout.getTabAt(i).setText(sectionsViewPagerAdapter.getPageTitle(i));
}
Om answered 17/12, 2015 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.