0

I am updating menuItem color at runtime throughout my app. And, I have come across a weird issue where setting ForegroundColorSpan using SpannableString is not working for API <= 24 or Android 7.0 and older. It works perfectly fine for API >= 25.

There are screenshots below showing the difference between Android 7.0 and Android 8.0 respectively.

Android 7.0

Android 8.0

Below is the helper method used to update each menuItem in menu.

public static void updateMenu(Menu menu, int iconColor) {
    if (menu != null) {
        MenuItem menuItem;
        for (int m = 0; m < menu.size(); m++) {
            menuItem = menu.getItem(m);
            if (menuItem.getIcon() != null) {
                DrawableCompat.setTint(DrawableCompat.wrap(menuItem.getIcon()), iconColor);
            }
            if (!TextUtils.isEmpty(menuItem.getTitle())){
                SpannableString spanString = new SpannableString(menuItem.getTitle());
                spanString.setSpan(new ForegroundColorSpan(iconColor), 0, spanString.length(), 0);
                menuItem.setTitle(spanString);
            }
            if (menuItem.getActionView() instanceof ImageView) {
                ImageView imageView = (ImageView) menuItem.getActionView();
                DrawableCompat.setTint(DrawableCompat.wrap(imageView.getDrawable()), iconColor);
            }
        }
    }
}

On searching the web for answers, I came across a few asking to set allCaps to false, but a menuItem does not have such property. One solution recommends using,

app:actionViewClass="androidx.appcompat.widget.AppCompatTextView"

but that too hasn't helped, as it takes away the clickable property of the menuItem and we have to separately handle clicks instead of all clicks to menuItem going to 'onOptionItemSelected()'.

Any kind of help in this matter is appreciated.

Bijon Desai
  • 60
  • 2
  • 10
  • I've tried your code and I can confirm it doesn't work. There are a lot of solutions [on this question](https://stackoverflow.com/questions/3519277), I'm sure some of them will work. I've tried the `Html.fromHtml` one and it didn't work. Subclassing the LayoutInflater is probably the best. – Nicolas Jun 16 '20 at 01:24
  • My answer on the linked duplicate shows how to apply that `textAllCaps` attribute. – Mike M. Jun 16 '20 at 01:58
  • 1
    @MikeM. Thank You. – Bijon Desai Jun 16 '20 at 03:12

0 Answers0