Fabii
Fabii

Reputation: 3890

How do I programmatically change ActionBar menuitem text colour?

I have an actionBar with multiple items, I would like to change the colour of the text when the item is clicked. Is there anyway to do this programmatically? Please provide and example or any resources.

Thanks

  public void catalogClick(MenuItem item){
     //highlight menuitem etc.

  }

Upvotes: 11

Views: 17273

Answers (3)

lucas_sales
lucas_sales

Reputation: 129

Try Firewall_Sudhan answer but iterating the submenu of the menu

@Override
public void onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    SubMenu subMenu = menu.getItem(0).getSubMenu();
    for (int i = 0; i <  subMenu.size(); i++) {
        MenuItem menuItem = subMenu.getItem(i);
        CharSequence menuTitle = menuItem.getTitle();
        SpannableString styledMenuTitle = new SpannableString(menuTitle);
        styledMenuTitle.setSpan(new ForegroundColorSpan(Color.BLACK), 0, menuTitle.length(), 0);
        menuItem.setTitle(styledMenuTitle);
    }
}

Upvotes: 1

MSD
MSD

Reputation: 2657

To change without defining a style resource, we can use SpannableString.

    @Override
public boolean onPrepareOptionsMenu(Menu menu) {
            //To style first menu item
    MenuItem menuItem = menu.getItem(0);
    CharSequence menuTitle = menuItem.getTitle();
    SpannableString styledMenuTitle = new SpannableString(menuTitle);
    styledMenuTitle.setSpan(new ForegroundColorSpan(Color.parseColor("#00FFBB")), 0, menuTitle.length(), 0);
    menuItem.setTitle(styledMenuTitle);

    return super.onPrepareOptionsMenu(menu);
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {

    Toast.makeText(this, item.getTitle() + " clicked!", Toast.LENGTH_LONG).show();
    return true;
}

As you format the text style, you will get "Invalid payload item type" exception. To avoid that, override onMenuItemSelected, and use return true or false.

Reference:

Android: java.lang.IllegalArgumentException: Invalid payload item type

http://vardhan-justlikethat.blogspot.in/2013/02/solution-invalid-payload-item-type.html

Upvotes: 4

Dexter
Dexter

Reputation: 1711

Follow this link which explains how to change menuitem text programmatically.

http://developer.android.com/guide/topics/ui/actionbar.html#Style

Check for android:actionMenuTextColor for defining a style resource for text.

Upvotes: 2

Related Questions