2016-02-17 75 views
1

我的工具栏标题需要能够根据按钮单击更改颜色。例如,工具栏标题的默认颜色是白色,但是如果按下按钮,我希望它变成红色。如何以编程方式更改工具栏文本的颜色

我尝试使用以下内容:

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

但由于某些原因的颜色只是不希望改变。它曾用于操作栏,但出于某种原因,这种方法不适用于工具栏。

回答

2

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

如果我只想改变标题颜色的一部分,该怎么办?只说出整个标题中的几个字母。我应该更具体,这就是我想要做的。 – Brejuro

+1

@Brejuro我编辑了我的答案。 – SilentKnight

+0

我想跨越我的工具栏标题,但不是textview。此外,在我的文章中,我试图使用SpannableString,但它似乎没有影响我的标题的颜色。感谢您与我保持联系 – Brejuro

5

您可以使用这样的事情:

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

使用V7程序兼容性库可以调用setTitleTextColor()工具栏上的

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

几个字母整个标题:

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

如果我只想更改部分标题颜色,该怎么办?只说出整个标题中的几个字母。我应该更具体,这就是我想要做 – Brejuro

+0

改变你的文字颜色将是棘手。你可能需要添加subtittle,并改变它的颜色,以检查这个http://www.coderzheaven.com/2014/10/09/change-title-subtitle-text-color-actionbar-android/ –

+0

@Brejuro检查这个更新回答 –

相关问题