我使用的是TextSwitcher,但是setText()方法接受的是CharSequence而不是resID整数。如果我使用getString(resID),格式化就会被剥离。有没有办法让格式化的文本(粗体和斜体)在TextSwitcher中显示
发布于 2011-09-05 18:16:53
了解SpannableStringBuilder,它在生成带样式的文本时非常有用。
然后创建您的格式化字符串,如下所示:
SpannableStringBuilder sb = new SpannableStringBuilder();
sb.append("Hi, abc!");
sb.setSpan(new ForegroundSpan(0xffff0000), 4, 7, 0); // set characters 4 to 7 to red
yourTextWidget.setText(sb, BufferType.SPANNABLE); 编辑: TextSwitcher只是ViewSwitcher的一个小包装器。检查TextSwitcher的源代码可以发现:
/**
* Sets the text of the next view and switches to the next view. This can
* be used to animate the old text out and animate the next text in.
*
* @param text the new text to display
*/
public void setText(CharSequence text) {
final TextView t = (TextView) getNextView();
t.setText(text);
showNext();
}因此,只需调用它而不是setText
final TextView t = (TextView) yourWidget.getNextView();
t.setText(sb, BufferType.SPANNABLE);
yourWidget.showNext();发布于 2011-09-05 18:13:15
为了将带格式的文本设置为TextView,您需要使用Html.fromHtml(String)。请记住,Spanned是从CharSequence实现的。
您还可以使用Resources.getText(int)从您的应用程序资源中获取带样式的CharSequence。
https://stackoverflow.com/questions/7306455
复制相似问题