Reputation: 3191
I have implemented a ´NavigationView´ which has a few menu options that when user selects one, it changes the "main fragment" view to anothers... My problem is, I'd like that when the user presses the back button, unless he is on the "main fragment" the screen returns to the "main fragment", otherwise close the app (regular onBackPressed() behaviour when there is no activity or backStack). What I've done so far:
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.debitsNavId:
getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment_container, new MainFragment(), "main_fragment").commit();
break;
case R.id.friendsNavId:
getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment_container, new FriendFragment(), "friend_fragment").commit();
break;
case R.id.notificationsNavId:
getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment_container, new RequestFragment(), "request_fragment").commit();
break;
case R.id.configurationsNavId:
Intent i = new Intent(MainActivity.this,
SettingsActivity.class);
startActivity(i);
break;
case R.id.logoutNavId:
logout();
break;
default:
return false;
}
menuItem.setChecked(true);
drawer_layout.closeDrawers();
return false;
}
The problem is, if the user navigates from 'FriendFragment' to 'RequestFragment' or vice-versa, the fragment that gets "backstacked" is the previous one (either FriendFragment or RequestFragment) and I'd like to still be "MainFragment".
How can I achieve that ?
Hope I made myself clear and thanks for your time !
Upvotes: 0
Views: 140
Reputation: 1710
So basically what you would need to do is that when the MainFrag is visible set a boolean to true and if you navigate away set it to false.
Then override the onBackPressed, in your main activity, like the following method:
@Override
public void onBackPressed() {
if (!isMainFragVisible) {
getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment_container, new MainFragment(), "main_fragment").commit();
}
}
You can set the isMainFragVisible to true in this method:
case R.id.debitsNavId:
getSupportFragmentManager().beginTransaction().replace(R.id.main_fragment_container, new MainFragment(), "main_fragment").commit();
isMainFragVisible = true
break;
And set it to false in any other navigation method.
Upvotes: 1
Reputation: 1568
do it this way
getSupportFragmentManager().beginTransaction().addToBackStack(fragment.getClass().getSimpleName()).replace(R.id.main_fragment_container, new MainFragment(), "main_fragment").commit();
Upvotes: 0