is there a way to dynamically update the title of a tab in a Design Support TabLayout? I tried adding a method in the Adapter which changes the contents of the ArrayList which holds the titles of the tabs and notify the adapter but the tab titles don't change to the new title.
Adapter:
public class TabAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragments = new ArrayList<>();
private final List<String> fragmentTiles = new ArrayList<>();
public TabAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment, String title) {
fragments.add(fragment);
fragmentTiles.add(title);
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
@Override
public CharSequence getPageTitle(int position) {
return fragmentTiles.get(position);
}
public void setFragmentTiles(int index, String title) {
fragmentTiles.set(index, title);
Log.e("ARRAY", fragmentTiles.toString());
}
}
I am changing the content of the title ArrayList like this:
adapter.setFragmentTiles("New title 1");
adapter.setFragmentTiles("New title 2");
adapter.notifyDataSetChanged();
But this doesn't work. Do I have to update the ViewPager or the TabLayout as well?
You can use any of the two way...the first one override the getPageTitle .. method of the adapter and set page title according to ur tabs position. The second way is in your activity while initializing the tabs..
The title and icon of Tabs are set through setText(int) and setIcon(int) methods of TabListener interface respectively. Tabs of layout are attached over TabLayout using the method addTab(Tab) method. We can also add tab item to TabLayout using TabItem of android design widget.
Find the view pager that will allow the user to swipe between fragments. Create an adapter that knows which fragment should be shown on each page. Set the adapter onto the view pager. Give the TabLayout the ViewPager.
What's worked for me is to use the setText method on the Tab:
i.e. tab.setText(...); // where ... is CharSequence or resId
Looking at the methods available to the TabLayout you can get the desired Tab instance of an index/position:
e.g. tabLayout.getTabAt(...); // where ... is int.
As far as I can tell, calling notifyDataSetChanged()
on the adapter just calls the getCount()
of the adapter as opposed to what one might expect of refreshing the title.
Hopefully that helps or at least points you in the right direction.
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