简体   繁体   English

如何以编程方式更改工具栏文本的颜色

[英]How to change the color of the Toolbar text programmatically

My toolbar title needs to be able to change color depending on button click. 我的工具栏标题需要能够根据按钮单击更改颜色。 For example, the default color for the toolbar title is white, but if I press a button, I want it to change to red for example. 例如,工具栏标题的默认颜色为白色,但如果按下按钮,我希望它更改为红色。

I tried using the following: 我尝试使用以下内容:

SpannableString title;
title.setSpan(new ForegroundColorSpan(Color.argb(1, 255, 64, 129)), 0, remainingTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

But for some reason the color just does not want to change. 但由于某种原因,颜色不想改变。 It used to work with actionbar, but for some reason this same method does not work with toolbar. 它曾经与actionbar一起使用,但由于某种原因,同样的方法不适用于工具栏。

You can use something like this: 你可以使用这样的东西:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Hello");
toolbar.setTitleTextColor(Color.RED);//for red colored toolbar title

Toolbar can change its text color. Toolbar可以更改其文本颜色。 So, just call Toolbar.setTitleTextColor(int color) . 所以,只需调用Toolbar.setTitleTextColor(int color)

If you want to span a text, you need to call TextView.setText(SpannableString) . 如果要跨越文本,则需要调用TextView.setText(SpannableString) Here is an example: 这是一个例子:

Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers"); 
//Handle with your Span here. Like change color of part text, bold or italic part text, add hypertext and something like that.
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
toolbar.setText(wordtoSpan);

Using the v7 appcompat library you can call setTitleTextColor() on the Toolbar 使用v7 appcompat库,您可以在工具栏上调用setTitleTextColor()

if (actionBarToolbar != null)
    actionBarToolbar.setTitleTextColor(Color.RED);

couple letters out of the entire title : 整个标题中的几个字母:

getActionBar().setTitle(Html.fromHtml("<font color='#ff0000'>YourColorText</font>") + "tittle");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM