Saturday, November 20, 2010

Using formatted text (in code) on Android

Putting text into a TextView on Android is easy - you just use TextView.setText(text) unlike other overloaded methods with the same name, you can not just use a String with Html formatting to format the passed text.

In order to do so, you either need to obtain the text from a resource file, use Html.fromHtml(String html) helper method or create a SpannableString that can then be passed to the method.

Html.fromHtml() is actually very convenient:

String s = "This is a <b>fat</b> string";
TextView tv = .. ;
tv.setText(Html.fromHtml(s));

But while working on Zwitscher I saw that Html.fromHtml() is actually very expensive to use, as internally it is using the whole arsenal of XML parsing.

Plan B is using SpannableString...

Creating such a text is a bit complicated as you need to deal with individual Spans and so on, which I found inconvenient.

So I've introduced a SpannableBuilder helper class to make this process easier.

Usage is as follows:

SpannableBuilder builder = new SpannableBuilder(context);
builder.append(status.getRetweetedStatus().getUser().getName(),Typeface.BOLD)      
.appendSpace()
      .append(R.string.resent_by, Typeface.NORMAL)                
      .appendSpace()                
      .append(status.getUser().getName(), Typeface.BOLD);
textView.setText(builder.toString());

Using this helper class does not trigger any XML parsing and is thus a lot faster than Html.fromHtml().

So far only methods that deal with TypeFaces are implemented, but extending the class for modifications of the background would be easy.

1 comment:

TsunamiHandia said...

Fantastic! Very usefull and easy. Thanks.