Skip to content Skip to sidebar Skip to footer

Change Toolbar Menu Item Text Color Dynamically On Different Android Version

Need to change toolbar menu item text color in different fragments. Right now i have two fragments when this must work. I set static style AppTheme with. textAllCaps attribute set to true, which causes an AllCapsTransformationMethod to be set on the titles' TextViews. That transformation method had a bug prior to Oreo, in that it would treat the text as a flat String, which essentially strips any formatting spans that you may have set.

This was corrected in Oreo, but since AllCapsTransformationMethod is a platform class, that fix isn't retroactive, even with the support/androidx libraries. For our own fix, we can simply turn off textAllCaps for those item titles, and handle the capitalization ourselves in code, before creating the formatted text.

For the support/androidx ActionBar/Toolbar, we modify the theme and style as such:

<style name="AppTheme" parent="Theme.AppCompat...">
    ...
    <item name="actionMenuTextAppearance">@style/TextAppearance.ActionBar.Menu.NoCaps</item>
</style>

<style name="TextAppearance.ActionBar.Menu.NoCaps"
       parent="TextAppearance.AppCompat.Widget.ActionBar.Menu">

    <item name="textAllCaps">false</item>
</style>

Then convert the title to uppercase in the code:

SpannableString s = new SpannableString(menuItem.getTitle().toString().toUpperCase());

For the platform ActionBar/Toolbar, we need to set the corresponding platform attributes in the theme and style. For example:

<style name="AppTheme" parent="android:Theme.Material...">
    ...
    <item name="android:actionMenuTextAppearance">@style/TextAppearance.ActionBar.Menu.NoCaps</item>
</style>

<style name="TextAppearance.ActionBar.Menu.NoCaps"
       parent="android:TextAppearance.Material.Widget.ActionBar.Menu">

    <item name="android:textAllCaps">false</item>
</style>

The code change is the same.


As this was fixed in Oreo, we could apply the above only on the affected versions by making these changes in the relevant res/values[-v??]/ folders, and using the default settings in res/values-v26/, and any higher.

However, it is much simpler to just set this style for all versions, and since the text processing we're doing is a little less intensive than what AllCapsTransformationMethod would do, there's really no reason not to use this everywhere.


Post a Comment for "Change Toolbar Menu Item Text Color Dynamically On Different Android Version"