首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TextSwitcher中的格式化文本?

TextSwitcher中的格式化文本?
EN

Stack Overflow用户
提问于 2011-09-05 17:58:17
回答 2查看 701关注 0票数 0

我使用的是TextSwitcher,但是setText()方法接受的是CharSequence而不是resID整数。如果我使用getString(resID),格式化就会被剥离。有没有办法让格式化的文本(粗体和斜体)在TextSwitcher中显示

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2011-09-05 18:16:53

了解SpannableStringBuilder,它在生成带样式的文本时非常有用。

然后创建您的格式化字符串,如下所示:

代码语言:javascript
复制
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的源代码可以发现:

代码语言:javascript
复制
/**
 * 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

代码语言:javascript
复制
final TextView t = (TextView) yourWidget.getNextView();
t.setText(sb, BufferType.SPANNABLE);
yourWidget.showNext();
票数 4
EN

Stack Overflow用户

发布于 2011-09-05 18:13:15

为了将带格式的文本设置为TextView,您需要使用Html.fromHtml(String)。请记住,Spanned是从CharSequence实现的。

您还可以使用Resources.getText(int)从您的应用程序资源中获取带样式的CharSequence

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7306455

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档