1

我想将我的工具栏标题设置为“视频(4)”,其中“视频”部分是一种颜色,“(4)”部分是另一种颜色。我想使用我的colors.xml资源文件中的颜色。工具栏标题中有多种颜色?

我该怎么做?

下面是我如何设置工具栏标题:

getSupportActionBar().setTitle("Videos (" + numVideos + ")"); 

回答

2

您可以设置自定义与spannable字体和颜色。

试试这个:

protected void setActionBarTitle(String title) { 
    //if API level below 18, there is a bug at Samsung and LG devices 
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) { 
     getSupportActionBar().setTitle(title); 
    } else { 
     SpannableString s = new SpannableString(title); 
     s.setSpan(new TypefaceSpan(this, "Your-Font.ttf"), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
     s.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent)), 0, s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 
     getSupportActionBar().setTitle(s); 
    } 


} 

在你的情况,这应该工作:

SpannableString firstPart = new SpannableString("Videos "); 
SpannableString lastPart = new SpannableString(" (4)"); 

firstPart.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getApplicationContext(), R.color.white)), 0, firstPart.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

lastPart.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getApplicationContext(), R.color.black)), 0, lastPart.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); 

然后设置你的标题thike这样的:

getSupportActionBar().setTitle(firstPart + lastPart); 

或像这样:

getSupportActionBar().setTitle(TextUtils.concat(firstPart, lastPart)); 
+0

这并不解释如何在单个工具栏标题中使用多种颜色。我也不想改变字体。 – user486123

+0

@ user486123起初,我告诉过你背后的逻辑。刚刚更新了我的答案/ –

+0

不得不使用'TextUtils.concat(firstPart,lastPart)'而不是'firstPart + lastPart',但谢谢! – user486123

0
String text = "<font color=#cc0029>Videos</font> <font color=#ffcc00>(" + numVideos + ")</font>"; 

getSupportActionBar().setTitle(Html.fromHtml(text)); 

+0

“我想使用'colors.xml'资源文件中的颜色。” – user486123

+0

这些情况下,您直接提到字体标签内的颜色 – sasikumar