Search code examples
androidandroid-actionbarmenuitemandroid-menu

How to override content description for an Action Bar MenuItem?


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?


Solution

  • OK, I've figured it out. Fortunately, I did not have to turn to the XML alternative. What I had to do was create a fresh View object, and apply it as the MenuItem's actionView. The hard part was actually to style the view object as any ordinary MenuItem would look like for the current theme (if I added it without using actionView). Follows the snippet (assuming the name of my activity is MyActivity):

        public boolean onCreateOptionsMenu(Menu menu) {
            Button buttonView = new Button(this, null, android.R.attr.actionButtonStyle);
            if (Build.VERSION.SDK_INT < 23) {
                buttonView.setTextAppearance(this, android.R.style.TextAppearance_DeviceDefault_Widget_ActionBar_Menu);
            } else {
                buttonView.setTextAppearance(android.R.style.TextAppearance_DeviceDefault_Widget_ActionBar_Menu);
            }
            buttonView.setText(R.string.option_title); // button label
            buttonView.setContentDescription("Content description");
            buttonView.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View view) {
                    MyActivity.this.onOptionsItemSelected(item);
                }
            });
    
            MenuItem item = menu.add(R.string.option_title);
            item.setActionView(buttonView);
            ...
            return super.onCreateOptionsMenu(menu);
        }