-2

Suppose I want to color part of text (words do you) in the sentence.

So I use this:

<string name="congratulations">Hello, how <font color="#00FFFF">do you</font> do</string>

But this not work on Android 4.0.

So for fix this I use next:

<string name="congratulations">Hello, how <font fgcolor="#FF00FFFF">do you</font> do</string>

But this not work for Android 4.3.

Has universal approach that will be work for all Android 4.0+ version AND for different languages?

I found that this not work on device: OS Version: 4.4.2 Device: HTC Desire 610. So at finally I use this solution:

<string name="expand"><![CDATA[<font color=#00FFFF>+</font> My contacts]]></string>. 

Of course you need in java code use this:

Html.fromHtml(source);  

So now it's work for all Adnroid 4.0+ and for all languages.

Alexei
  • 14,350
  • 37
  • 121
  • 240

2 Answers2

5

I've done something quite similar with SpannableString. look at this example:

String a = getString(R.string.string1);
String b = getString(R.string.string2);

Spanned color1 = setSpanColor(a,Color.CYAN);
Spanned color2 = setSpanColor(b,Color.RED);
Spanned mixedColor = TextUtils.concat(color1, " ", color2);
// Now use `mixedColor`

setSpanColor

public Spanned setSpanColor(String string, int color){
    SpannableStringBuilder builder = new SpannableStringBuilder();
    SpannableString ss = new SpannableString(string);
    ss.setSpan(new ForegroundColorSpan(color), 0, string.length(), 0);
    //ss.setSpan(new StyleSpan(Typeface.ITALIC), 0, string.length(), 0);
    builder.append(ss);
    return ss;
}

Update

Another way is to do it with Html format wich supports all API levels as well:

Spanned text;
String yourText = getResources().getString(R.string.congratulations);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
    // For API 24(nougat)+
    text =(Html.fromHtml("<font color='#FFEB3B'><b>"+yourText+"</b></font>",Html.FROM_HTML_MODE_LEGACY));
} else {
     // pre API 24
     text =(Html.fromHtml("<font color='#FFEB3B'><b>"+yourText+"</b></font>"));
}
// Now use `text`
S.R
  • 2,819
  • 2
  • 22
  • 49
0

Along @S.R answer you may Try dynamically. got from here

TextView TV = (TextView)findViewById(R.id.mytextview01);

Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");        

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

TV.setText(wordtoSpan);
Faisal Naseer
  • 4,110
  • 1
  • 37
  • 55
  • what about multi languages? Scope from 15 to 30 is correct for English, but not correct fro Spain (from 16 to 37). – Alexei Jun 10 '17 at 11:38