i have Fragment Activity With contatin navigation drawer.after clicking navigation drawer item it open a Fragment 1, fragment 2, Fragment 3.and then after button click event in Fragment 1 open new Fragment 4.
i want handle back key press event how can i do this on Fragment 4?after clicking back key in Fragment 4 i want to go back Fragment 1.
Add Fragments To BackStack. Before commit() the transaction, use addToBackStack() method i.e
addToBackStack("Some String").commit();
and in onBackPressed()
@Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
getSupportFragmentManager().popBackStack();
} else {
this.finish();
}
}
Your code for adding fragment to backstack should be like:
getFragmentManager() .beginTransaction() .replace(R.id.content_frame, Entry_Account.newInstance(), Entry_Account.TAG).addToBackStack("Some string") .commit();
Then On Activity's onBackPressed method,use this snippet:
@Override
public void onBackPressed () {
if(getFramentManager().getBackStackEntryCount()>0){
// popback statck.
}
else{
// finish your activity.
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With