I\'m having trouble changing androids action bar title color programmatically for v11 and up. I can get it done in xml but need to change it dynamically in code. How should
Another way is using Html
getSupportActionBar().setTitle((Html.fromHtml("<font color=\"#FF4444\">" + getString(R.string.some_string) + "</font>")));
If you use Sherlock Actionbar you may use the sherlock-actionbar-id for supported actionbars (Android below 3.0)
int titleId = Resources.getSystem().getIdentifier("action_bar_title", "id", "android");
if ( 0 == titleId )
titleId = com.actionbarsherlock.R.id.abs__action_bar_title;
The ActionBar
title ID is hidden, or in other words, it's internal and accessing it can't be done typically. You can reference it using Resources.getIdentifier
then View.findViewById
though.
Grab the ID for the action_bar_title
int titleId = getResources().getIdentifier("action_bar_title", "id", "android");
Now you can use the ID with a TextView
TextView abTitle = (TextView) findViewById(titleId);
abTitle.setTextColor(colorId);
You can use a SpannableString and ForegroundColorSpan to set the colour of the title
Spannable text = new SpannableString(actionBar.getTitle());
text.setSpan(new ForegroundColorSpan(Color.BLUE), 0, text.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
actionBar.setTitle(text);
If using the v7 appcompat library (tested with r22) then you can call setTitleTextColor() on the Toolbar
object that substitutes the action bar for all API levels. For example:
Toolbar actionBarToolbar = (Toolbar)activity.findViewById(R.id.action_bar);
if (actionBarToolbar != null)
actionBarToolbar.setTitleTextColor(Color.RED);
Using Kotlin and SupportActionBar Use this ->
val mSpannableText = SpannableString(supportActionBar?.title)
mSpannableText.setSpan(
ForegroundColorSpan(Color.BLUE),
0,
mSpannableText.length,
Spannable.SPAN_INCLUSIVE_INCLUSIVE
)
supportActionBar?.title = mSpannableText