How do I programmatically change ActionBar menuitem text colour?

醉酒当歌 提交于 2019-12-05 15:24:04

问题


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.

  }

回答1:


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.




回答2:


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




回答3:


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);
    }
}


来源:https://stackoverflow.com/questions/9895472/how-do-i-programmatically-change-actionbar-menuitem-text-colour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!