Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

handle back button in single fragment

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?

like image 605
Rahul Ahuja Avatar asked Nov 01 '22 04:11

Rahul Ahuja


1 Answers

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();
    }
}
like image 189
dora Avatar answered Nov 14 '22 00:11

dora