How to Add a Custom Item to a Navigationview with a Menu Layout

How can I add a custom item to a NavigationView with a menu layout?

The actionLayout attribute is now supported in Android Support Library 23.1:

NavigationView provides a convenient way to build a navigation drawer, including the ability to creating menu items using a menu XML file. We’ve expanded the functionality possible with the ability to set custom views for items via app:actionLayout or using MenuItemCompat.setActionView().

So the code in the question should just work now.

NavigationView custom menu item

I solved it - I used the ViewTreeObserver to update the items programmatically. I will leave the solution here as it might help someone.

//handle the navigation drawer item
val navViewTreeObserver = navView.viewTreeObserver
navViewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
navView.viewTreeObserver.removeOnGlobalLayoutListener(this)
val menu = navView.menu
//get the menu items of the navigation view
for (i in 0 until menu.size()){
val menuItem = menu.getItem(i)
//get the relevant views that we want to change programmatically
val menuItemText = menuItem.actionView.findViewById<TextView>(R.id.navItemText)
val menuItemIcon = menuItem.actionView.findViewById<ImageView>(R.id.navItemIcon)
//change the menu item's text and icon depending on the position in the drawer
when (i){
0 -> {
menuItemText.text = "Document Scan"
menuItemIcon.setImageResource(R.drawable.nav_icon_qr_scan)
}
1 -> {
menuItemText.text = "Activity Reports"
menuItemIcon.setImageResource(R.drawable.nav_icon_report_inactive)
}
2 -> {
menuItemText.text = "Hall of fame"
menuItemIcon.setImageResource(R.drawable.nav_icon_hall_of_fame_inactive)
}
}
}
}
})

NavigationView menu items with actionLayout. How can I set those action layout's attribute for each item?

Good! @ianhanniballake 's suggested method worked like a charm. If I do this:

NavigationView nav_v = findViewById(R.id.navigation_view);
MenuItem nav_option1 = nav_v.getMenu().findItem(R.id.menu_item1);
ImageView option1_lock_icon = nav_option1.getActionView().findViewById(R.id.lockedIcon);

And from there, I could do whatever I want with this ImageView:

// Toggle visibility approach
if (item_locked) {
option1_lock_icon.setVisibility(View.VISIBLE);
} else {
option1_lock_icon.setVisibility(View.INVISIBLE);
}

// Change icon approach
string uri = "";
if (item_locked) {
uri = "@android:drawable/ic_lock_idle_lock";
} else {
uri = "@android:drawable/ic_menu_view";
}
int imageResource = getResources()
.getIdentifier(uri,
null,
getPackageName()
);
option1_lock_icon.setImageDrawable(
getResources().getDrawable(imageResource)
);

Also, it looks like I can do more or less the same with any object I add to those "action layouts". :-)



Related Topics



Leave a reply



Submit