How to change action bar title color in code

前端 未结 6 1250
陌清茗
陌清茗 2020-11-27 05:28

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

相关标签:
6条回答
  • 2020-11-27 06:03

    Another way is using Html

    getSupportActionBar().setTitle((Html.fromHtml("<font color=\"#FF4444\">" + getString(R.string.some_string) + "</font>")));
    
    0 讨论(0)
  • 2020-11-27 06:03

    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;
    
    0 讨论(0)
  • 2020-11-27 06:12

    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);
    
    0 讨论(0)
  • 2020-11-27 06:15

    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);
    
    0 讨论(0)
  • 2020-11-27 06:15

    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);
    
    0 讨论(0)
  • 2020-11-27 06:17

    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
    
    0 讨论(0)
提交回复
热议问题