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



我的工具栏标题需要能够根据按钮单击更改颜色。例如,工具栏标题的默认颜色是白色,但是如果我按下按钮,我希望它更改为红色。

我尝试使用以下方法:

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

但出于某种原因,颜色就是不想改变。它曾经与操作栏一起使用,但由于某种原因,这种方法不适用于工具栏。

你可以使用这样的东西:

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

Toolbar可以更改其文本颜色。所以,只需打电话给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);

使用 v7 appcompat 库,您可以在工具栏上调用setTitleTextColor()

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

整个标题中的几个字母:

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

最新更新