Android 文本切换器中的格式化文本?

Android 文本切换器中的格式化文本?,android,android-widget,Android,Android Widget,我使用的是TextSwitcher,但是setText()方法接受的是CharSequence而不是resID整数。如果我使用getString(resID)格式将被剥离。是否有方法获取格式化文本(粗体和斜体)以在文本切换器中显示?要将格式化文本设置为文本视图,您需要使用。请记住,span从CharSequence执行 您还可以使用从应用程序资源中获取样式化的CharSequence。要将格式化文本设置为TextView,您需要使用。请记住,span从CharSequence执行 您还可以使用从

我使用的是
TextSwitcher
,但是
setText()
方法接受的是
CharSequence
而不是resID整数。如果我使用
getString(resID)
格式将被剥离。是否有方法获取格式化文本(粗体和斜体)以在
文本切换器中显示?

要将格式化文本设置为
文本视图,您需要使用。请记住,
span
CharSequence
执行


您还可以使用从应用程序资源中获取样式化的
CharSequence

要将格式化文本设置为
TextView
,您需要使用。请记住,
span
CharSequence
执行


您还可以使用从应用程序资源中获取样式化的
CharSequence

了解
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();

了解
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();

我尝试了这个,但是TextSwitcher似乎仍然忽略了我字符串中的标记。我尝试了这个,但是TextSwitcher似乎仍然忽略了我字符串中的标记。这个注释字段不支持丰富的格式,所以我只编辑上面的答案:)谢谢!这只需要一个小改动,我需要将“t.setText(sb,BufferType.SPANNABLE);”替换为“t.setText(R.string.blah);”这个注释字段不支持丰富的格式,所以我只需编辑上面的答案:)谢谢!这只需要一个小改动,我需要将“t.setText(sb,BufferType.SPANNABLE);”替换为“t.setText(R.string.blah);”