如何通过编程更改工具栏文本的颜色

3
我的工具栏标题需要能够根据按钮点击更改颜色。例如,默认情况下工具栏标题的颜色为白色,但如果我按下一个按钮,我希望它更改为红色。
我尝试使用了以下代码:
SpannableString title;
title.setSpan(new ForegroundColorSpan(Color.argb(1, 255, 64, 129)), 0, remainingTitle.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

但是由于某些原因,颜色就是不想改变。它曾经在ActionBar中起作用,但由于某种原因,这个方法在工具栏中无法正常工作。

3个回答

8
你可以使用类似这样的方式:

你可以像这样使用:

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

3

工具栏可以更改其文本颜色。因此,只需调用Toolbar.setTitleTextColor(int color)

如果您想跨度一个文本,您需要调用TextView.setText(SpannableString)。以下是一个例子:

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

如果我只想改变标题的一部分颜色怎么办?比如说只有整个标题中的几个字母。我应该更具体地说明,这就是我想做的事情。 - Brejuro
我想要跨越我的工具栏标题,而不是一个文本视图。此外,在我的帖子中,我尝试使用SpannableString,但似乎没有影响我的标题的颜色。感谢您一直陪伴着我。 - Brejuro

3
使用 v7 appcompat 库,您可以在工具栏上调用 setTitleTextColor() 方法。
if (actionBarToolbar != null)
    actionBarToolbar.setTitleTextColor(Color.RED);

标题中只有几个字母:

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

如果我只想改变标题的一部分颜色怎么办?比如说只有整个标题中的几个字母。我应该更具体地说明,这就是我想做的事情。 - Brejuro
更改标题文本的颜色可能有些棘手。您可能需要添加副标题并更改其颜色。请查看此链接以了解如何实现:http://www.coderzheaven.com/2014/10/09/change-title-subtitle-text-color-actionbar-android/ - Amit Vaghela

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接