textview上的颜色和样式操作

Luk*_*kap 2 string android coding-style colors textview

好吧想象我们有这样的文字

String s="123 45678 91011122314 1516";
Run Code Online (Sandbox Code Playgroud)

现在我的问题是我想这么说

textview.setText(stylemystring(s));
Run Code Online (Sandbox Code Playgroud)

我希望'123'是粗体和红色,45678是斜体和蓝色,等等

我发现在设计这些东西时很有问题,有html格式的解决方案,但问题是应该是红色或蓝色的文本的大小是动态的,所以我需要更灵活的东西.

谢谢

Gre*_*ory 10

这样的事情应该有效:

    SpannableStringBuilder text = new SpannableStringBuilder("123 45678 91011122314 1516");
    text.setSpan(new ForegroundColorSpan(Color.RED), 0, 3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    text.setSpan(new ForegroundColorSpan(Color.BLUE), 4, 9, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    text.setSpan(new StyleSpan(Typeface.BOLD), 4, 9, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
    textView.setText(text, TextView.BufferType.SPANNABLE);
Run Code Online (Sandbox Code Playgroud)

您可以将不同的样式添加到String的不同部分.基于http://developer.android.com/resources/faq/commontasks.html#selectingtext