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.
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.