I have created a tablayout in MainActivity and bunch of fragments using viewpager. I want to change the color of tablayout when I click a button present in fragment. So how do I refer to tablayout created in MainActivity so that I can change it's color in respective fragments?
Asked
Active
Viewed 234 times
0
-
I'd say create the method to change tab colors in MainActivity. Then create nested interfaces in the fragments and implement these interfaces in MainActivty. Check this link for more info about communication between fragment -> activity. https://stackoverflow.com/questions/14247954/communicating-between-a-fragment-and-an-activity-best-practices – Vanheden Jun 16 '21 at 05:02
1 Answers
1
You can change background color of tablayout using addOnTabSelectedListener
of tablyout
according to position of tabs, like below code:
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) {
}
});

Android Geek
- 8,956
- 2
- 21
- 35