How to override content description for an Action Bar MenuItem?

Viewed 2263

I have an ActionBar for which I add a couple of MenuItems objects inside the Activity's onCreateOptionsMenu(Menu) method. But I need to override the content description for one of these items.

I've been thinking about defining the MenuItem in XML and setting up the actionViewClass attribute. And back in source code, call MenuItem.getActionView() for the MenuItem, just like described in http://developer.android.com/training/appbar/action-views.html. That way I could call setContentDescription() on the View object it returns. But I would rather do that without using XML file.

Does anyone has any ideas besides using the XML option?

2 Answers

I had to do it recently for my app and the selected answer helped me, posting selected answer In Kotlin:

val profileIcon = ImageButton(context)
profileIcon.setImageResource(R.drawable.icon_profile)
profileIcon.background = null
profileIcon.contentDescription = "Profile"
val item: MenuItem = menu.add("Profile")
item.setShowAsAction(SHOW_AS_ACTION_ALWAYS)
item.actionView = profileIcon
profileIcon.setOnClickListener {
    onOptionsItemSelected(item)
}
super.onCreateOptionsMenu(menu, inflater)
Related