【问题标题】:Change word color in resource string更改资源字符串中的单词颜色
【发布时间】:2012-03-09 14:12:55
【问题描述】:

有没有办法在android中设置字符串资源的颜色?我的意思是,我知道我可以使用一些 html 标签来更改字符串样式(或子字符串),但没有找到任何可以更改颜色的标签。我在 stackoverflow 看到了其他解决方案,例如在设置文本之前将字符串传递给 Html.fromHtml(string) 但我想在字符串资源编辑器中进行。有没有可能?

【问题讨论】:

    标签: android string android-widget


    【解决方案1】:

    看起来this 方法有效:

        <string name="some_text">this is <font fgcolor="#ffff0000">red</font></string>
    

    【讨论】:

    • 它似乎在 4.3 中停止工作(可能更早)——有人知道发生了什么吗?
    • Why it stopped working, how it stopped working, a nice workaround / involves code :( 和一个丑陋的解决方法:对于高于 7fffffff 的任何颜色,应用以下内容:&lt;font color="#ff6890a5"&gt;ff6890a5 放入计算器(可选转换为十进制首先)并翻转符号,然后(可选地转换回十六进制)取最后 8 个十六进制数字并使用&lt;font color="-#00976F5B"&gt;
    • 好的,现在真是太棒了。它工作得很好。非常感谢,我希望我很久以前就知道这一点。
    • 请注意,任何使用这种方法的人都应该使用Resources.getText(id:) 方法来获取字符串,而不是Resources.getString(id:) 方法。前一种方法在 String 中保留任何富文本样式,而后者则不保留。此外,使用Resources.getText(id:) 方法,您可以在font 元素中使用color 属性而不是fgcolor
    【解决方案2】:

    据我所知,这是不可能的。我会使用 SpannableString 来改变颜色。

        int colorBlue = getResources().getColor(R.color.blue);
        String text = getString(R.string.text);
        SpannableString spannable = new SpannableString(text);
        // here we set the color
        spannable.setSpan(new ForegroundColorSpan(colorBlue), 0, text.length(), 0);
    

    Spannable 真的很棒。您可以在其中设置诸如 fontseize 之类的想法,然后将其附加到文本视图中。优点是您可以在一个视图中拥有不同的颜色。

    编辑:好的,如果你只想设置颜色,我上面提到的解决方案就是要走的路。

    【讨论】:

    • 我明白了,如果这是要走的路,我可以创建我的字符串资源,其中包含一些“代码”,以了解我想要更改颜色的子字符串的开始和结束位置并以这种方式处理它你暴露了。谢谢。
    • int colorBlue = getResources().getColor(R.color.blue); .... spannable.setSpan(new ForegroundColorSpan(colorBlue), 0, text.length(), 0); 可以用这样的单行替换spannable.setSpan(new ForegroundColorSpan(R.color.blue) ..
    • 另外,我个人会使用在 spannable 类中声明的标志常量,而不是在调用期间硬编码 0。使代码更具可读性和可维护性。只是我会做的事情..
    【解决方案3】:

    字符串本身没有颜色,但是你可以在它们出现的textView中改变文本的颜色。参见textview documentation,但是有2种方法可以做到。

    XML

    android:textColor
    

    代码

    setTextColor(int)
    

    【讨论】:

    • 感谢您的回答。我认为它没有很好地制定。我指的是更改资源字符串中子字符串的颜色。很抱歉。
    【解决方案4】:

    我最近为这个问题做了一个灵活的解决方案。它使我能够通过使用方法链接轻松地将多种样式添加到子字符串中。它使用 SpannableString。当你想给某个子字符串一个颜色时,你可以使用 ForegroundColorSpan。

    public StyledString putColor(String subString, @ColorRes int colorRes){
        if(getStartEnd(subString)){
            int color = ColorUtil.getColor(context, colorRes);
            ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(color);
            fullStringBuilder.setSpan(foregroundColorSpan, startingIndex, endingIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return this;
    }
    

    完整代码见gist

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 2015-12-22
    • 2014-10-24
    • 2017-06-18
    相关资源
    最近更新 更多