I have an application with navigation drawer. when i start the application, what i have on main screen (screen A) is "hello world" and then when i select an item from navigation drawer, i load a fragment and get "new hello world" and then again when i select an item from navigation drawer, i load a fragment and get "hello universe". But since this is all happening via 1 single fragment, when i press the device back button i should get previous fragment like below:
"hello universe" >press back> "new hello world" >press back> "hello world"
how do i handle this ?
NOTE:
while changing the fragment i have tried
fragmentManager.beginTransaction().replace(R.id.mainContent, fragment).commit();
then i changed to :
fragmentManager.beginTransaction().add(R.id.mainContent, fragment).addToBackStack("tag").commit();
but nothing worked. The app exits on back button press. Is it due to the same fragment getting replaced by another content again and again?
The second approach you tried is correct.Try to call popBackStack()
on BackPressed()
by overriding onBackPressed()
method.
@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else if (getFragmentManager().getBackStackEntryCount() == 0) {
super.onBackPressed();
}
}
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