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

后端 未结 11 2850
南笙
南笙 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-19 08:50

    Hello Friends Try This

    first add this method

      private void updateCounter() {
        try {
            for (int i = 0; i < tabLayout.getTabCount(); i++) {
                updateTab(tabLayout.getTabAt(i));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    second add this Method

       private void updateTab(TabLayout.Tab tab) {
        Method method;
        try {
            method = TabLayout.Tab.class.getDeclaredMethod("getCustomView");
            method.setAccessible(true);
    
            View tabView = (View) method.invoke(tab, new Object[0]);
    
            TextView tv_title = null;
    
            if (tabView != null) {
                tv_title = tabView.findViewById(R.id.tv_title);
            }
    
            switch (tab.getPosition()) {
                case 0:
                    if (tv_title != null) {
                        tv_title.setText(tabTitle[0]);
    
                        if(viewPager.getCurrentItem() == 0){
                            tv_title.setTypeface(CustomerApplication.getInstance().getMontserratBold());
                        }else{
                            tv_title.setTypeface(CustomerApplication.getInstance().getMontserratMedium());
                        }
                    }
                    break;
    
                case 1:
                    if (tv_title != null) {
                        tv_title.setText(tabTitle[1]);
    
                        if(viewPager.getCurrentItem() == 1){
                            tv_title.setTypeface(CustomerApplication.getInstance().getMontserratBold());
                        }else{
                            tv_title.setTypeface(CustomerApplication.getInstance().getMontserratMedium());
                        }
                    }
                    break;
            }
            tab.setCustomView(tabView);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    last call view pager change listener

    private final ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    
        }
    
        @Override
        public void onPageSelected(int position) {
            updateCounter();
        }
    
        @Override
        public void onPageScrollStateChanged(int state) {
    
        }
    };
    

提交回复
热议问题