【问题标题】:How to change background color of Tablayout from a fragment?如何从片段更改 Tablayout 的背景颜色?
【发布时间】:2021-08-31 21:35:21
【问题描述】:
我在 MainActivity 中创建了一个 tablayout,并使用 viewpager 创建了一堆片段。
当我单击片段中存在的按钮时,我想更改 tablayout 的颜色。
那么如何引用在 MainActivity 中创建的 tablayout 以便我可以在各个片段中更改它的颜色呢?
【问题讨论】:
标签:
android
android-layout
android-fragments
android-tablayout
【解决方案1】:
您可以根据选项卡的位置使用tablyout 的addOnTabSelectedListener 更改选项卡布局的背景颜色,如下面的代码:
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) {
}
});