Ishan hrx Ishan hrx - 2 months ago 52
Android Question

How to handle BackPress in fragments?

I have multiple fragments in my Application, and doubleBackPress to exit. The problem is, the doubleBackPress to exit is being activated no matter which fragment is being displayed on the activity.

Here is what I tried.

The code in MainActivity

@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
if (doubleBackToExitPressedOnce) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
return;
}

this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();

new Handler().postDelayed(new Runnable() {

@Override
public void run(){
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}


This is how I am launching the fragments.

fragmentManager = getFragmentManager() ;
fragmentTransaction = fragmentManager.beginTransaction();
CategoryFragment categoryFragment = new CategoryFragment();
fragmentTransaction.replace(R.id.container,categoryFragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();

Answer Source

You can refer to below code for your need. If you are not using v4 support fragment, then you have to use getFragmentManager() instead of getSupportFragmentManager() to get the backstack count. Here I am using boolean value to check if back is clicked, if in 2 seconds it is not clicked again, it will become false again.

boolean doubleBackToExitPressedOnce = false;
    @Override
    public void onBackPressed() {
        //Checking for fragment count on backstack
        if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
            getSupportFragmentManager().popBackStack();
        } else if (!doubleBackToExitPressedOnce) {
            this.doubleBackToExitPressedOnce = true;
            Toast.makeText(this,"Please click BACK again to exit.", Toast.LENGTH_SHORT).show();

            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    doubleBackToExitPressedOnce = false;
                }
            }, 2000);
        } else {
            super.onBackPressed();
            return;
        }
    }

I hope this may help you.