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?
I think you need to add the fragment to the backstack by calling addToBackStack, something like this:
and the override OnBackPressed():
use methods addToBackStack and popBackStack in order to handle back button for fragments here is sample
and on back button
The second approach you tried is correct.Try to call
popBackStack()
onBackPressed()
by overridingonBackPressed()
method.