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?
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) {
}
});