Fondesa Fondesa - 2 months ago 49
Android Question

TabLayout update tab content with a custom view

I'm using

TabLayout
of the new material design and i have a problem, i can't update tab content of a custom view once the tab is created:

I can simplify my method inside my PagerAdapter with

public View setTabView(int position, boolean selected) {
View v = LayoutInflater.from(context).inflate(R.layout.default_tab_view, null);
tv = (TextView) v.findViewById(R.id.tabTextView);
if(selected)
tv.setText("SELECTED");
else
tv.setText("UNSELECTED");
return v;
}


And in activity i can simplify my code with:

TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
ViewPager pager = (ViewPager) findViewById(R.id.viewpager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
tabLayout.setupWithViewPager(pager);
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
View v;
if (i == 0) {
v = adapter.setTabView(i, true);
v.setSelected(true);
} else
v = adapter.setTabView(i, false);

tab.setCustomView(v);
}

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
adapter.setTabView(tab.getPosition(), true);
}

@Override
public void onTabUnselected(TabLayout.Tab tab) {
adapter.setTabView(tab.getPosition(), false);
}

@Override
public void onTabReselected(TabLayout.Tab tab) {

}
});


The tabs' titles are set right when the app starts but when i change tab, the content still remains the same.

Answer

Ok I think it's bug on android design support library.

Because You are talking about the changes in content but I can't change the color of Text. Once the tab are created and if you change the layout it will not reflecting.

And As i have seen your code you are giving the custom layout using setCustomView. and for changing a text you are calling again the method setTabView(). Instead of that there should be method getCustomView() so that you can change the layout. There is a method in a TabLayout.Tab.getCustomView but it doesn't have identifier and I have report this bug.

https://code.google.com/p/android/issues/detail?id=177492

[Update 08-07-2015]

Finally bug is accepted by android bug source traking and marked as Future Release . So we can say that bug will no more exist on future library. and we can have method getCustomView() so that we can easily get our custom view.

[Update 18-08-2015]

Finally the bug is resolved Released in the v23 support libs . Just update support library using SDK manager and you have getCustomView() as a public.

just change this line in gradle

compile 'com.android.support:design:23.0.0'

and make sure compile and target sdk set to 23.