Onbackpressed Change Tabs In Android
I am looking for explanation for onBackPressed() change my tabs i have 3 different tabs in my activity. Requirement : If user accessing tab 2 and he pressed back button. app will
Solution 1:
Simply override onBackPressed()
as below:
overridefunonBackPressed() {
if (tabLayout.selectedTabPosition != 0) {
tabLayout.getTabAt(0)?.select()
} else {
super.onBackPressed()
}
}
Solution 2:
You can take switch case inside back press .
overridefunonBackPressed() {
when (mTabLayout.selectedTabPosition) {
0 -> super.onBackPressed()
1 -> mTabLayout.getTabAt(0)!!.select()
2 -> mTabLayout.getTabAt(1)!!.select()
}
}
In java
@Override
publicvoidonBackPressed() {
switch (mTabLayout.getSelectedTabPosition()) {
case0:
super.onBackPressed();
break;
case1:
mTabLayout.getTabAt(0).select();
break;
case2:
mTabLayout.getTabAt(1).select();
break;
}
}
Post a Comment for "Onbackpressed Change Tabs In Android"