I made a NavigationView on MainActivity (AppCompatActivity). I have multiple items on that NavigationView each one is a Fragment.
When I use back button I want to go to previous Fragment instead of put my app on background. Thus to change between Fragments I use:
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.layout, fragment).addToBackStack(null).commit();
When I press back button it goes to the previous Fragment, but the item checked of NavigationView remains. Which is the best way to update item checked of NavigationView on back button press?
i have used the following code into my project....and it worked.... I have inflated menu items into navigation drawer..... you have to implement it in your every fragment...in onActivityCreated() method....because this method will certainly called after activity is created so we can use UI elements...
//code.....
NavigationView navigation = (NavigationView)getActivity().findViewById(R.id.navigation_view);
Menu drawer_menu = navigation.getMenu();
MenuItem menuItem;
menuItem = drawer_menu.findItem(R.id.Id_ofYourMenuItem);
if(!menuItem.isChecked())
{
menuItem.setChecked(true);
}
So, every time your fragment is called(via navigation drawer or via pressing back button) ,it will set menu item checked itself.
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