Question

I am preparing an app that contains a checkbox for customizing style such as bold, italic, underline, color, etc... I am a little bit confused about which method is good for performance. I have tried typeface, but when user selects two checkboxes, it displays the last value only. It did not work well.

Était-ce utile?

La solution

Typeface is a graphics element used by Paint object for drawing text. It specifies the font (e.g. Monospace, Sans Serif, Serif, etc.) and the style of font (e.g. Bold, Italic, etc.) and is internally used by both Spannable and Html.

So the performance comparison should be done between Spannable and Html.

Html.fromHtml is a costlier operation as it involves parsing the Html. I used following code with Traceview and did the comparison between Html and Spannable. It basically sets the text bold and sets up the hyperlink.

Debug.startMethodTracing("htmlspan");
Spanned s1 = Html.fromHtml("<b>text1: Constructed from HTML programmatically.</b> Click <a href=\"http://www.google.com\">Link</a> ");
tv1.setText(s1);
Debug.stopMethodTracing();
tv1.setMovementMethod(LinkMovementMethod.getInstance());

Debug.startMethodTracing("normalspan");
SpannableString s2 = new SpannableString("text2: Constructed from JAVA programmatically. Click here.");
s2.setSpan(new StyleSpan(Typeface.BOLD), 0, 45, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
s2.setSpan(new URLSpan("http://www.google.com"),53,53+4, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
tv2.setText(s2);
Debug.stopMethodTracing();
tv2.setMovementMethod(LinkMovementMethod.getInstance());

Result:

  • Html API : ~14-15ms. (org.ccil.cowan.tagsoup.Parser.parse API took around 12.282ms)
  • Spannbale API : ~1-2ms.

TraceView for Html API: TraceView for Html API

TraceView for Spannable API: TraceView for Spannable API

Summary: Performance point of view using directly Spannable is faster compared to Html.

Autres conseils

Spannable internally uses Typeface. Spannable is provided by android framework to ease the development. Hence use Spannable.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top