Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change the text style of a selected tab when using tabLayout?

Tags:

android

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.

like image 252
Felipe Calderon Avatar asked Aug 16 '15 03:08

Felipe Calderon


People also ask

How do you change the text color on a selected tab?

Right-click the worksheet tab whose color you want to change. Choose Tab Color, and then select the color you want. The color of the tab changes, but not the color of the font.


2 Answers

I changed the answer suggested above a bit and it works great for me, no additional .xml files needed, hope it will help.

for (int i = 0; i < tabLayout.getTabCount(); i++) {

    TabLayout.Tab tab = tabLayout.getTabAt(i);
    if (tab != null) {

        TextView tabTextView = new TextView(this);
        tab.setCustomView(tabTextView);

        tabTextView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
        tabTextView.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;

        tabTextView.setText(tab.getText());

        // First tab is the selected tab, so if i==0 then set BOLD typeface
        if (i == 0) {
            tabTextView.setTypeface(null, Typeface.BOLD);
        }

    }

}

tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());

        TextView text = (TextView) tab.getCustomView();

        text.setTypeface(null, Typeface.BOLD);
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        TextView text = (TextView) tab.getCustomView();

        text.setTypeface(null, Typeface.NORMAL);
    }

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

    }

});
like image 115
user1974368 Avatar answered Oct 01 '22 01:10

user1974368


If you use default TabLayout (not customView), you can get TextView of tab by using getChildAt() method.

.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            LinearLayout tabLayout = (LinearLayout)((ViewGroup) mMainTabs.getChildAt(0)).getChildAt(tab.getPosition());
            TextView tabTextView = (TextView) tabLayout.getChildAt(1);
            tabTextView.setTypeface(tabTextView.getTypeface(), Typeface.BOLD);
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            LinearLayout tabLayout = (LinearLayout)((ViewGroup) mMainTabs.getChildAt(0)).getChildAt(tab.getPosition());
            TextView tabTextView = (TextView) tabLayout.getChildAt(1);
            tabTextView.setTypeface(null, Typeface.NORMAL);
        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) { }
    });
like image 35
hoi Avatar answered Oct 01 '22 03:10

hoi