如何从片段更改 Tablayout 的背景颜色?

How to change background color of Tablayout from a fragment?

我在 MainActivity 中创建了一个 tablayout,并使用 viewpager 创建了一堆片段。 单击片段中的按钮时,我想更改 tablayout 的颜色。 那么我如何引用在 MainActivity 中创建的 tablayout 以便我可以在各个片段中更改它的颜色?

您可以根据标签的位置使用 addOnTabSelectedListenertablyout 更改标签布局的背景颜色,如下面的代码:

     tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    viewPager.setCurrentItem(tab.getPosition());
                    switch (tab.getPosition()){
// Change color of tab layout according to tab position
 
                        case 0:
                            tabLayout.setBackgroundColor(getResources().getColor(R.color.black));
                            break;
                        case 1:
                            tabLayout.setBackgroundColor(getResources().getColor(R.color.teal_200));
                            break;
                        default:
                            tabLayout.setBackgroundColor(getResources().getColor(R.color.black));
                            break;
    
                    }
                }
    
                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
    
                }
    
                @Override
                public void onTabReselected(TabLayout.Tab tab) {
    
                }
            });