Android TabLayout select first Tab on Startup
I had a similar problem with a custom tab layout I was implementing, when starting the activity the first tab wouldn't appear in the selected state but tab 2,3,4... would when auto-selected on startup.
The solution that helped me was in onResume()
, quickly select the second tab then return to the first tab.
@Override
protected void onResume() {
super.onResume();
mTabLayout.getTabAt(1).select();
mTabLayout.getTabAt(0).select();
}
I got it. The solution is simple, use (once) onTabReselected and overwrite listener there.
tabLayout.setOnTabSelectedListener(new OnTabSelectedListener() {
@Override
public void onTabSelected(Tab tab) {
selectTab(tab);
}
private void selectTab(Tab tab) {
// do something
}
@Override
public void onTabReselected(Tab tab) {
if (tab.getPosition() == 0) {
selectTab(tab);
tabLayout.setOnTabSelectedListener(new OnTabSelectedListener() {
@Override
public void onTabSelected(Tab tab) {
selectTab(tab);
}
@Override
public void onTabReselected(Tab arg0) {
}
@Override
public void onTabUnselected(Tab arg0) {
}
});
}
}
@Override
public void onTabUnselected(Tab tab) {
}
});