onBackPressed change tabs in android

2019-08-29 01:43发布

问题:

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 send him to tab 1

Looking for explanation with code

Here is my app view

Thanks you

回答1:

Simply override onBackPressed() as below:

override fun onBackPressed() {
    if (tabLayout.selectedTabPosition != 0) {
        tabLayout.getTabAt(0)?.select()
    } else {
        super.onBackPressed()
    }
}


回答2:

You can take switch case inside back press .

override fun onBackPressed() {


    when (mTabLayout.selectedTabPosition) {
        0 -> super.onBackPressed()
        1 -> mTabLayout.getTabAt(0)!!.select()
        2 -> mTabLayout.getTabAt(1)!!.select()
    }
}

In java

@Override
public void onBackPressed() {
    switch (mTabLayout.getSelectedTabPosition()) {
        case 0:
            super.onBackPressed();
            break;
        case 1:
            mTabLayout.getTabAt(0).select();
            break;
        case 2:
            mTabLayout.getTabAt(1).select();
            break;
    }
}