Search code examples
javaandroidandroid-fragmentsandroid-tabs

How to Implement onBackPressed for Android Fragments(Tabs Activity)


I am developing an Android Application which contains the Tabs Activity. My Tabs activity contains four tabs(Fragments--[1][2][3][4]). What I want is when I press the Back button it must be redirected to the previous tab, not to the first tab. Like

[4] -> [3]
[3] -> [2]
[2] -> [1]
[1] -> Alert to logout from the App

Please help me out. What do I have to write in my TabsActivity class.


Solution

  • Use logics instead of hardcoding page numbers. Below solution works with 2,3,... n, every number of items in Viewpager.

    @Override
    public void onBackPressed() {
        if (viewPager.getCurrentItem() != 0) {
            viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
        } else super.onBackPressed();
    }
    

    If you are using TabHost then you can use this solution.