I want to make the text of a selected tab bold. How can I do this either through xml or java code, whatever is easier.
There is a way to add bold programmatically by using a Tab CustomView, loading a TextView into that CustomView and applying styling on the TextView:
private TabLayout mTabLayout;
protected void onCreate(Bundle savedInstanceState) {
...
mTabLayout = (TabLayout) findViewById(R.id.tablayout);
mTabLayout.setOnTabSelectedListener(new OnTabSelectedListener());
int tabCount = mTabLayout.getTabCount();
for (int i = 0; i < tabCount; i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
if (tab != null) {
TextView tabTextView =
(TextView) LayoutInflater.from(this).inflate(R.layout.tab_item, mTabLayout, false);
tabTextView.setText(tab.getText());
// First tab is the selected tab, so if i==0 then set Tabs_Selected style
tabTextView.setTextAppearance(getAppContext(), i == 0 ? R.style.TextAppearance_Tabs_Selected
: R.style.TextAppearance_Tabs);
tab.setCustomView(tabTextView);
}
}
}
class OnTabSelectedListener implements TabLayout.OnTabSelectedListener {
public void onTabSelected(TabLayout.Tab selectedTab) {
int tabCount = mTabLayout.getTabCount();
for (int i = 0; i < tabCount; i++) {
TabLayout.Tab tab = mTabLayout.getTabAt(i);
View tabView = tab != null ? tab.getCustomView() : null;
if (tabView instanceof TextView) {
((TextView) tabView).setTextAppearance(getAppContext(), selectedTab.equals(tab)
? R.style.TextAppearance_Tabs_Selected
: R.style.TextAppearance_Tabs);
}
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
And here is the entries in styles.xml:
And here is the layout tab_item: