Reputation: 423
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();
Upvotes: 0
Views: 587
Reputation: 548
You are replacing fragment try this :
fragmentTransaction.add(R.id.container,categoryFragment);
instead of
fragmentTransaction.replace(R.id.container,categoryFragment);
Upvotes: 0
Reputation: 8272
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.
Upvotes: 1