Reputation: 26387
I have text that I load from an external source. I can control how the external source defines the string.
text = "foo<font color='red'>bar</font>foo"
text2 = "foofoo<font color='red'>bar</font>foo"
Is there a way to specify that Android isn't supposed to use the standard CSS color red but the red I define in my colors.xml
file?
I want to call createColoredText(text)
and then have my TextView with the correct color.
Upvotes: 1
Views: 1314
Reputation: 26387
I solved my problem myself with regex:
public static Spanned formatTextForTextView(String text, Context context){
text = replaceColorForHex(text, "blue", R.color.blue, context);
text = replaceColorForHex(text, "green", R.color.green, context);
text = replaceColorForHex(text, "red", R.color.red, context);
return Html.fromHtml(text);
}
private static String replaceColorForHex(
String text,
String colorString,
int colorId,
Context context
){
String colorHex = getColorHex(colorId, context);
Pattern pattern = Pattern.compile(
"(<font[^>]+color=)(['" + '"' + "]"
+ colorString
+ "['" + '"' + "])([^>]*>)"
//Captures a <font color='colorString'> html tag.
//Allows for additional attributes within the font
//tag
);
Matcher matcher = pattern.matcher(text);
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
matcher.appendReplacement(
sb, matcher.group(1) + colorHex + matcher.group(3));
}
matcher.appendTail(sb);
text = sb.toString();
return text;
}
private static String getColorHex(int colorId, Context context){
int colorContent = context.getResources().getColor(colorId);
return String.format("#%06X", (0xFFFFFF & colorContent));
}
Upvotes: 1
Reputation: 181
Use Spannable String to Changing of Coloring Text in TextView.
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append("My string. I ").append(" ");
builder.setSpan(new ImageSpan
(getApplicationContext(),R.mipmap.ic_launcher),builder.length() - 1,
builder.length(), 0);
builder.append("Cree by Dexode test");
builder.setSpan(new ClickableSpan() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Test", Toast.LENGTH_LONG).show();
}
@Override
public void updateDrawState(TextPaint ds) {
super.updateDrawState(ds);
ds.setUnderlineText(false);
ds.setARGB(255, 255, 255, 255);
}
}, 30, 41, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
txt.setMovementMethod(LinkMovementMethod.getInstance());
txt.setText(builder);
Upvotes: 0
Reputation: 1226
You can do this using Spannable String
Spannable wordtoSpan = new SpannableString("YOUR TEXT");
int startIndex=7, endIndex=9;
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), startIndex, endIndex, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TEXTVIEW.setText(wordtoSpan);
Upvotes: 0