android - 工具栏标题中有多种颜色?

标签 android android-layout android-studio android-toolbar android-styles

我想将工具栏标题设置为“视频 (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/

相关文章:

android - 如何通过 Firebase 电子邮件/密码身份验证获取 UID 并添加用户信息

android - 使用应用程序更新 ListView 小部件

android - 使用 Appium 测试多个 Activity

android - 两个带 Android 的屏幕/显示器?

Android - 从通知操作按钮调用方法

java - 检查互联网连接 OKHTTP

Android WebView 显示纯文本

android - 像菜单项一样的路径 - Android

java - Android Studio中执行aapt失败

使用 layout_gravity ="bottom||end"xml 时 Android 资源链接失败