Change word color in resource string

前端 未结 4 1577
暖寄归人
暖寄归人 2020-12-01 19:16

Is there anyway to set the color of a string resource in android? I mean, I know I can use some html tags to change string style (or substrings) but have not found any to ch

相关标签:
4条回答
  • 2020-12-01 19:35

    I have recently made a flexible solution for this problem. It enables me of easily add multiple styles to substrings by using method chaining. It makes use of the SpannableString. When you want to give a certain substring a color, you can use 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;
    }
    

    For full code see gist.

    0 讨论(0)
  • 2020-12-01 19:36

    The strings themselves have no color, but you can change the color of the text in the textView they appear in. See the textview documentation, but there are 2 ways to do it.

    XML

    android:textColor
    

    Code

    setTextColor(int)
    
    0 讨论(0)
  • 2020-12-01 19:44

    It looks like this method is working:

        <string name="some_text">this is <font fgcolor="#ffff0000">red</font></string>
    
    0 讨论(0)
  • 2020-12-01 19:47

    As far as I know it is not possible. I would use a SpannableString to change the color.

        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 is really nice. You can set thinks like fontseize and stuff there and just attach it to a text view. The advantage is that you can have different colors in one view.

    Edit: Ok, if you only want to set the Color the solution mentioned above me is the way to go.

    0 讨论(0)
提交回复
热议问题