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

后端 未结 11 2862
南笙
南笙 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:43

    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:

    
    
    

提交回复
热议问题