4

What do I do if tv.setText(Html.fromHtml(text)); takes too long, and hangs the UI? If I can do it with a thread, can you provide an example?

OkyDokyman
  • 3,786
  • 7
  • 38
  • 50

2 Answers2

6
private Handler mHandler = new Handler() {
     void handleMessage(Message msg) {
          switch(msg.what) {
               case UPDATE_TEXT_VIEW:
                    tv.setText(msg.obj); // set text with Message data
                    break;
          }
     }
}

Thread t = new Thread(new Runnable() {
     // use handler to send message to run on UI thread.
     mHandler.sendMessage(mHandler.obtainMessage(UPDATE_TEXT_VIEW, Html.fromHtml(text));
});
t.start();
Robby Pond
  • 73,164
  • 16
  • 126
  • 119
3

If you don't need to parse long or complex HTML, manual composing of Spannable is much faster than using Html.fromHtml(). Following sample comes from Set color of TextView span in Android

TextView TV = (TextView)findViewById(R.id.mytextview01);
Spannable wordtoSpan = new SpannableString("I know just how to whisper, And I know just how to cry,I know just where to find the answers");
wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
TV.setText(wordtoSpan);
Community
  • 1
  • 1
tomash
  • 12,742
  • 15
  • 64
  • 81