Skip to content
pyricau edited this page Jan 14, 2012 · 8 revisions

Since AndroidAnnotations 2.2

How to inject Html text in TextViews? See @HtmlRes and @FromHtml.

If you want to inject HTML text in a TextView (may it be to format it or because you love HTML), there are two annotations that can help you:

  • @FromHtml
  • @HtmlRes

@HtmlRes

This annotation acts as @StringRes and adds a call to HTML.fromHtml:

@HtmlRes(R.string.hello_html)
Spanned myHelloString;

@HtmlRes
CharSequence helloHtml;

Equivalent boilerplate code:

Spanned myHelloString;

CharSequence hello;

@Override
public void onCreate(Bundle savedInstanceState) {
    [...]
    myHelloString = Html.fromHtml(getString(R.string.hello_html));
    hello = Html.fromHtml(getString(R.string.hello_html));
}

Note that Spanned implements CharSequence, thus you can use both for a @HtmlRes.

@FromHtml

This annotation must be used on a TextView with @ViewById. The purpose of this annotation is to set HTML text in a TextView:

@ViewById(R.id.my_text_view)
@FromHtml(R.string.hello_html)
TextView textView;

@ViewById
@FromHtml
TextView someView;

Equivalent boilerplate code:

TextView textView;

TextView someView;

@Override
public void onCreate(Bundle savedInstanceState) {
    [...]
    textView = ((TextView) findViewById(id.my_text_view));
    someView = ((TextView) findViewById(id.someView));
    if (textView!= null) {
        textView.setText(Html.fromHtml(getString(string.hello_html)));
    }
    if (someView!= null) {
        someView.setText(Html.fromHtml(getString(string.someView)));
    }
}

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Clone this wiki locally