Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  }
like image 596
Fabii Avatar asked Mar 27 '12 18:03

Fabii


People also ask

How do I change the text color of popup menu in android programmatically?

The code used is: PopupMenu popupMenu = new PopupMenu(mContext, mImageView); popupMenu. setOnMenuItemClickListener(MyClass. this); popupMenu.

How can change Actionbar background color in android programmatically?

To change background color of Action Bar in Kotlin Android, set the colorPrimary in themes. xml, with a required color. We can also dynamically change the background color of Action Bar programmatically by setting background drawable for support action bar with the required color drawable.

How do I change the color of the menu text?

Android App Development for Beginners This example demonstrates how do I change the text color of the menu item in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.


1 Answers

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

like image 93
Firewall_Sudhan Avatar answered Oct 20 '22 06:10

Firewall_Sudhan