How to change action bar title color in code

2019-01-06 15:38发布

问题:

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 I go about this? Thanks in advance.

回答1:

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);


回答2:

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);


回答3:

Another way is using Html

getSupportActionBar().setTitle((Html.fromHtml("<font color=\"#FF4444\">" + getString(R.string.some_string) + "</font>")));


回答4:

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);


回答5:

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;