我想将工具栏标题设置为“视频 (4)”,其中“视频”部分是一种颜色,“(4)”部分是另一种颜色。我想使用 colors.xml
资源文件中的颜色。
我该怎么做?
以下是我设置工具栏标题的方法:
getSupportActionBar().setTitle("Videos (" + numVideos + ")");
最佳答案
您可以使用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);
然后将你的标题设置为这样:
getSupportActionBar().setTitle(firstPart + lastPart);
或者像这样:
getSupportActionBar().setTitle(TextUtils.concat(firstPart, lastPart));
关于android - 工具栏标题中有多种颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43433954/