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?
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With