Reputation: 709
I have implemented new Navigation view in navigation drawer. Now I want to hide and show the logout menu item on several login and logout condition.
here is my menu item of navigation view
<group android:checkableBehavior="single">
<item
android:id="@+id/home"
android:checked="false"
android:icon="@drawable/drawer_ic_home"
android:title="@string/home_string" />
<item
android:id="@+id/offer_coffee"
android:checked="false"
android:icon="@drawable/drawer_ic_offer_coffee"
android:title="@string/offer_coffee_string" />
<item
android:id="@+id/share_coffee"
android:checked="false"
android:icon="@drawable/drawer_ic_share_coffee"
android:title="@string/share_coffee_string" />
<item
android:id="@+id/take_coffee"
android:checked="false"
android:icon="@drawable/drawer_ic_take_coffee"
android:title="@string/take_coffee_string" />
<item
android:id="@+id/offer_status"
android:checked="false"
android:icon="@drawable/drawer_ic_coffee"
android:title="@string/offer_status"
/>
<item
android:id="@+id/about_us"
android:checked="false"
android:icon="@drawable/drawer_ic_about_us"
android:title="@string/about_us_string" />
<item
android:id="@+id/logout"
android:checked="false"
android:icon="@drawable/logout"
android:title="@string/logout" />
</group>
I want to hide the Logout item if I am not login and if I am login then I want to show this sub menu.
I have seen several links but they all are working on group of items but in my case I have to access single sub menu item named Logout in the group .
Upvotes: 3
Views: 1846
Reputation: 709
Thanks all for helping me , I was doing exactly both same things answered above. but some how I managed to do it in different way and that is to get the tile of the menu item clicked and then comparing it , if the item title is logout , and if I am logged in (As per my case ) do what ever I want.
Upvotes: 0
Reputation: 7659
The whole menu is indexed from 0
to n
from top to bottom. So you have two groups with 5 item each then it is from 0 to 9.
private boolean ifNotLoggedIn;
private NavigationView navigationView;
...
protected void onCreate(Bundle savedInstanceState) {
...
if(ifNotLoggedIn){
navigationView.getMenu().getItem(7).setVisible(false);
}
}
Edit
As @Moinkhan pointed out, we can use the findById()
method as well to do the similar.
navigationView.getMenu().getItem(R.id.logout).setVisible(false);
Upvotes: 3
Reputation: 12932
It's simple just add the following code.
I am assuming that you are taking isUserLoggedIn
boolean variable to store user login state.
navigationView = (NavigationView) findViewById(R.id.nav);
Menu menu = navigationView.getMenu();
if (! isUserLoggedIn) {
menu.findItem(R.id.logout).setVisible(false);
}
Upvotes: 2