How to change selected tab title textSize in Android

后端 未结 3 1149
轻奢々
轻奢々 2021-01-15 16:55

I am trying to find a way to change text size of Tab Title when selected. Until now without exit. Hope someone can help me.

My code bellow:

XML

3条回答
  •  不知归路
    2021-01-15 17:30

    I would recommend to set custom tab.

    First you need to initiate your custom tabs, otherwise it won't change anything.

    1. Create a new layout with a TextView (you can add whatever you want to be in each tab).
    2. In your onActivityCreated after your tabLayout.setupWithViewPager initiate your custom tabs:

      for (int i = 0; i < 3; i++) { // 3 - A+B+C in your example
          TabLayout.Tab tab = tabLayout.getTabAt(i);
          if (tab != null) {
              ViewGroup tabContainer = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.custom_tab_item, tabLayout, false);
              if (tabContainer != null) {
                  TextView yourTv = (TextView) tabContainer.findViewById(R.id.tv); 
                  yourTv.setTextSize(18);
                  tab.setCustomView(tabContainer);
              }
          }
      }
      
    3. Add listener tabLayout.addOnTabSelectedListener and Implement TabLayout.OnTabSelectedListener, In your onTabSelected use this:

      for (int i = 0; i < tabLayout.getTabCount(); i++) {
          TabLayout.Tab tab = tabLayout.getTabAt(i);
          if (tab != null) {
              View customView = tab.getCustomView();
              if (customView != null) {
                  TextView yourTv = (TextView) customView.findViewById(R.id.tv);
                  if (yourTv != null) {
                      if (i == selectedTabIndex) {
                          yourTv.setTextSize(18);
                      } else {
                          yourTv.setTextSize(16);
                      }
                  }
              }
          }
      }
      

提交回复
热议问题