开发者

Formatted text in TextSwitcher?

I'm using a TextSwitcher, however the setText() method takes in a CharSequence rather than an resID integer. If I use getString(resID) the formatting is stripped out. Is 开发者_如何学Pythonthere a way to get formatted text (with bold and italics) to show in a TextSwitcher?


Learn about SpannableStringBuilder, this is so useful in producing styled text.

Then just create your formatted strings like:

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); 

Edit: TextSwitcher is just a small wrapper to ViewSwitcher. Examining the sources of TextSwitcher reveals:

/**
 * 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();
}

So, just call this instead of setText:

final TextView t = (TextView) yourWidget.getNextView();
t.setText(sb, BufferType.SPANNABLE);
yourWidget.showNext();


In order to set a formatted text to a TextView, you need to use Html.fromHtml(String). Keep in mind, Spannedimplements from CharSequence.

You can also use Resources.getText(int) to get a styled CharSequence from your application resources.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜