How To Close One Fragment When Isvisible
Hello i having an activity with fragment. I can just open one fragment when i click on icon or something like this But i want to close a fragment(or hide) with OnBackPressed method
Solution 1:
Override onBackPressed
in your activity. If there is any fragment in backstack than popBackStack()
otherwise simply finish()
your activity.
private boolean allowedToExit = false; // class level
@Override
public void onBackPressed() {
int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount();
// this is the last item
if (backStackEntryCount == 1) {
if (allowedToExit)
finish();
else {
allowedToExit = true;
Toast.makeText(this, "Press again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
allowedToExit = false;
}
}, 1000);
return;
}
}
// we have more than 1 fragments in back stack
if (backStackEntryCount > 1) {
getSupportFragmentManager().popBackStackImmediate();
// getSupportFragmentManager().beginTransaction().commit();
} else
super.onBackPressed();
}
Post a Comment for "How To Close One Fragment When Isvisible"