寻求最简单的方法让TextView的文本以不同的颜色着色

时间:2012-12-13 14:10:49

标签: android

我希望文本视图显示的某些字符串为红色,有些黑色,我该怎么做?

有没有办法在XML文件中简单提一下? (strings.xml)

3 个答案:

答案 0 :(得分:2)

我认为你可以使用span。 Text Style

例如,

   final SpannableStringBuilder sb = new SpannableStringBuilder(" text must be here ");
   final ForegroundColorSpan fc1 = new ForegroundColorSpan(Color.rgb(255, 0, 0)); 
   final ForegroundColorSpan fc2 = new ForegroundColorSpan(Color.rgb(255, 255, 255)); 
   sb.setSpan(fc1 , 0, 4, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 
   sb.setSpan(fc2, 5, 8, Spannable.SPAN_INCLUSIVE_INCLUSIVE); 
   yourTextView.setText(sb);

(或)

在样式XML中,声明颜色值如下所示

<color name="redColor">#ff0000</color>

并在布局xml中使用它,用于textColor属性,

android:textColor="@color/redColor"

答案 1 :(得分:1)

你可以试试这个,

String.replaceAll(textToHighlight,<font color="red">textToHighlight</font>);

Textview.setText(Html.fromHtml(String));

答案 2 :(得分:0)

我认为这样做的唯一方法是使用如下的跨区类型。

TextView textview = (TextView)findViewById(R.id.myTextview);
String firstName = "FirstName";
String lastName = "LastName";
Spanned details = Html.fromHtml(firstName + "<br />" + "<small><font color=\"#767676\">" + lastName + "</b></small>");
textview.setText(details);

希望这有帮助

相关问题