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

后端 未结 11 2858
南笙
南笙 2021-02-19 07:57

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.

11条回答
  •  遥遥无期
    2021-02-19 08:52

    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) {
    
        }
    
    });
    

提交回复
热议问题