Akash Desai Akash Desai - 9 months ago 27
Android Question

cannot go back to previous fragments or activity with single tap

Hi I'm trying to go back to my previous

activity/fragment
when back is pressed.

Suppose I have my main fragment as main screen, from there i go to an activity.now when i press back.. it quits the app.. i need to go to main fragment. how to do this? i need to go back to the
main fragment. as normal back works. but i don't know where i have made a mistake:

my java code is here.. or try the app..

code from activity:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// handle arrow click here
if (item.getItemId() == android.R.id.home) {
finish(); // close this activity and return to preview activity (if there is any)
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
doubleBackToExitPressedOnce = false;
}
}, 1000);
}


the above is my code from my
activity
.i don't know where my mistake is. may be i made mistake in
onoptionsitemselected
? or other thing maybe.

finish()
does it needs a return true as i found out on other questions ? earlier when pressing back from 1 activity to another worked properly.. but when i used fragments it was an issue..

Answer Source

This is what I do:

@Override
public void onBackPressed() {

    FragmentManager mgr = getFragmentManager();

    if (mgr.getBackStackEntryCount() > 0)
        mgr.popBackStack();
    else
        super.onBackPressed();
}

You will need to adjust it a bit for your desired "double click to exit" behavior.