-2

I want to create 3 tabs and each one have single fragment,when i press back button in device instead of closing of app i need to go previous tab.I had try a lot but not find correct answer which is suitable for my app.I am new to development.

What i have in my project is 3 tabs when i am at tab 3 if i press it needs to go tab 2 instead of closing app.

What ever suggestions i get those are helped only go back to previous fragment. But i want go to previous tab when we press back button in android device.

4 Answers4

1

This can be easily achieved by overriding onBackPressed(). The key here is to keep track of your current fragment and swatch tabs based on that info.

@Override
public void onBackPressed() {
    switch(activeFragment){
        case 3: triggerTab2();
            break;
        case 2: triggerTab1();
           break;
        case 1: super.onBackPressed();
            break;
    }
}
MrJM
  • 1,214
  • 1
  • 12
  • 26
0

For creating Tabs with fragments Check this link - http://www.androidhive.info/2015/09/android-material-design-working-with-tabs/

For on Back button pressed you need to override onBackPressed() in the activity not in fragments. You need to handle back pressed and provide index of respective tab.

Hope it will help

Onkar Nene
  • 1,359
  • 1
  • 17
  • 23
0

Use this

  @Override
public void onBackPressed() {
    // put switch or if which decide which fragment 
    Class fragmentClass = Fragment.class;
            Fragment fragment = null;
            try {
                fragment = (Fragment) fragmentClass.newInstance();
            } catch (java.lang.InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            ((Activity) getContext()).getSupportFragmentManager().beginTransaction()
                    .replace(R.id.content_fragment, fragment).commit();

            // R.id.content_fragment => id of viewPager
}
Vishwesh Jainkuniya
  • 2,821
  • 3
  • 18
  • 35
0

If you have different fragments in one tab if you press back button by using OnBackPressed() we can go for previous fragment.For that situation following code will help you.

    @Override 
public void On BackPressed(){
//You can check by write toast if it working are not.
FragmentManager manager = getSupportFragmentManager();
if (manager.getBackStackEntryCount() > 0) {
    // If there are back-stack entries, leave the FragmentActivity
    // implementation take care of them.
    //implement your code here.

    super.onBackPressed();
 }
}

It will help you to go back of your previous fragments not previous tabs.

this will help you understand. Separate Back Stack for each tab in Android using Fragments

Community
  • 1
  • 1
YBDevi
  • 439
  • 5
  • 22