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