Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change word color in resource string

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 change color. I have seen other solutions here at stackoverflow like passing the string to Html.fromHtml(string) before setting the text but I want to do it in the string resource editor. Any possibility?

like image 922
Notbad Avatar asked Mar 09 '12 14:03

Notbad


People also ask

How do I change text color in XML?

Android TextView – Text Color. TextView Text Color – To change the color of text in TextView, you can set the color in layout XML file using textColor attribute or change the color dynamically in Kotlin file using setTextColor() method.

How can I change the color of part of a string in Android?

MainActivity. SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(text2); // It is used to set foreground color. ForegroundColorSpan green = new ForegroundColorSpan(Color. GREEN);


2 Answers

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.

like image 137
Norman Avatar answered Oct 20 '22 13:10

Norman


It looks like this method is working:

    <string name="some_text">this is <font fgcolor="#ffff0000">red</font></string>
like image 39
Kapé Avatar answered Oct 20 '22 12:10

Kapé