Issue
I have a navigation drawer implemented but the problem is when the back button is pressed, the checked item in the draw does not correspond to the current fragment (only the last fragment that was actually added through the nav drawer)
There is a solution to this here: Updating the Navigation Drawer (with DrawerLayout) when back button is pressed
The solution states the following:
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
FragmentManager fm = getSupportFragmentManager();
String stackName = null;
for(int entry = 0; entry < fm.getBackStackEntryCount(); entry++){
stackName = fm.getBackStackEntryAt(entry).getName();
Log.i("BC", "stackEntry" + entry);
}
if (stackName == "Fragment1"){
mDrawerList.setItemChecked(0, true);
} else if (stackName == "Fragment2") {
mDrawerList.setItemChecked(1, true);
}
});
The issue with that is the conditional. Having to manually change the index of the nav item to be checked is a pain when you have a lot of items
What I want to do is listen for a change in the backstack, and if detected, get the id of the current fragment (as defined in the layout file) and pass that through to navigationView.setCheckedItem()
to automatically check the corresponding nav item. Something like this:
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setCheckedItem(R.id.nav_new);
In my mainactivity class, how do I get the id of the current fragment in the form R.id.xxx
so I can pass it through to setCheckedItem
?
Solution
You could do this
While adding the fragment do this
FragmentTransaction.addToBackStack(""+R.id.nav_new); // Use the id of navigation item which was clicked.
Then
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
FragmentManager fm = getSupportFragmentManager();
String stackName = null;
for(int entry = 0; entry < fm.getBackStackEntryCount(); entry++){
stackName = fm.getBackStackEntryAt(entry).getName();
Log.i("BC", "stackEntry" + entry);
}
int navItemId = -1;
try{
navItemId = Integer.parseInt(stackName);
} catch(NumberFormatException nfe) {
}
if(navItemId > 0){
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setCheckedItem(navItemId);
}
else
Log.e("", "Couldn't find the id");
});
NOTE: Whatever you will pass in addToBackStack
will be returned back to you when you will use getName()
on FragmentManager.BackStackEntry
Answered By - Rohit5k2
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.