Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Html.fromHtml takes too long

Tags:

android

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?

like image 992
OkyDokyman Avatar asked Jan 22 '23 20:01

OkyDokyman


2 Answers

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();
like image 114
Robby Pond Avatar answered Feb 01 '23 15:02

Robby Pond


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);
like image 33
tomash Avatar answered Feb 01 '23 17:02

tomash