I have implemented navigation drawer, it is working fine. The only problem that I have to make selected item to deselect when the navigationdrawer closes. I wonder how could I able to get the index value of selected menu item.
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(false);
}
)}
You have to use OnNavigationItemSelectedListener(MenuItem item) method.
The navigation drawer is a UI panel that shows your app's main navigation menu. The drawer appears when the user touches the drawer icon in the app bar or when the user swipes a finger from the left edge of the screen.
To use a DrawerLayout, position your primary content view as the first child with width and height of match_parent and no layout_gravity> . Add drawers as child views after the main content view and set the layout_gravity appropriately. Drawers commonly use match_parent for height with a fixed width.
One way to do is store menu item ID in variable e.g checkedItemID
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItemID=menuItem.getItemId();
}
)}
Then on implement
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
// Do whatever you want here
navigationView.getMenu().findItem(menuItemID).setChecked(false);
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// Do whatever you want here
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
Make a variable position of int
datatype. Firstly set its value to 0 and onNavigationItemSelected change its value to menuItem
index(like 0 or 1 or 2 and so on).Now this position will provide you the index of selected menuItem
.
int position = 0;
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.first:
position = 0;
break;
case R.id.second:
position = 1;
break;
case R.id.third:
position = 2;
break;
}
return true;
}
});
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