无法在android中为跨区字符串设置颜色

时间:2012-04-24 06:09:36

标签: android

我正在尝试为Spanned String添加颜色,但颜色不适用。它显示相同的颜色

作为文本视图颜色。我写的代码。

TextView desc2=(TextView)listrow.findViewById(R.id.desc222);
desc2.setText(Html.fromHtml("<font color='#811c1d'><b>MyText</b></font>&nbsp;&nbsp;").toString());

如果我删除“toString()”它会抛出

04-24 06:20:58.750: E/AndroidRuntime(309): java.lang.StackOverflowError
04-24 06:20:58.750: E/AndroidRuntime(309):  at java.lang.reflect.Array.newInstance(Array.java:473)
04-24 06:20:58.750: E/AndroidRuntime(309):  at android.text.SpannableStringInternal.getSpans(SpannableStringInternal.java:243)
04-24 06:20:58.750: E/AndroidRuntime(309):  at android.text.Styled.drawUniformRun(Styled.java:61)
04-24 06:20:58.750: E/AndroidRuntime(309):  at android.text.Styled.drawDirectionalRun(Styled.java:298)
04-24 06:20:58.750: E/AndroidRuntime(309):  at android.text.Styled.drawText(Styled.java:357)
04-24 06:20:58.750: E/AndroidRuntime(309):  at android.text.Layout.drawText(Layout.java:1387)
04-24 06:20:58.750: E/AndroidRuntime(309):  at android.text.Layout.draw(Layout.java:370)
04-24 06:20:58.750: E/AndroidRuntime(309):  at android.text.BoringLayout.draw(BoringLayout.java:365)
04-24 06:20:58.750: E/AndroidRuntime(309):  at android.widget.TextView.onDraw(TextView.java:4050)
04-24 06:20:58.750: E/AndroidRuntime(309):  at android.view.View.draw(View.java:6740)

任何人都可以告诉我问题是什么

2 个答案:

答案 0 :(得分:1)

试试这个:

TextView desc2=(TextView)listrow.findViewById(R.id.desc222);
desc2.setText(Html.fromHtml("<font color='#811c1d'><b>MyText</b></font>&nbsp;&nbsp;"));

答案 1 :(得分:1)

您可以使用SpannableString:

    SpannableString spanned = new SpannableString("MyText");
    ForegroundColorSpan fcs = new ForegroundColorSpan(yourColor);
    spanned.setSpan(fcs, 0, "MyText".length() - 1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    yourTextView.setText(spanned);