Html Tag Handler not called in Android N for “ul”, “li”

一曲冷凌霜 提交于 2019-12-23 07:36:59

问题


We have a custom TagHandler in our app for bulleted list etc.

html = "<ul><li>First item</li><li>Second item</li></ul>";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
  result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY, null, new ListHTMLTagHandler(density));
} else {
  //noinspection deprecation
  result = Html.fromHtml(html, null, new ListHTMLTagHandler(density));
}

The handleTag() function in my TagHandler is called for ul, li in API-23 and below but not called in API-24 (Android N).


回答1:


It is evident from the source of Html.java that, TagHandler.handleTag() is called only if the framework doesn't process it, itself.

Currently, the framework doesn't seem to process it well.

But even if it did it well, you would want to customize it anyway. The best way to deal with this is to replace the default ul, li tags with your own tags. Since the framework won't process your custom tags, your TagHandler will be asked to handle it.

public static String customizeListTags(@Nullable String html) {
  if (html == null) {
    return null;
  }
  html = html.replace("<ul", "<" + UL);
  html = html.replace("</ul>", "</" + UL + ">");
  html = html.replace("<ol", "<" + OL);
  html = html.replace("</ol>", "</" + OL + ">");
  html = html.replace("<dd", "<" + DD);
  html = html.replace("</dd>", "</" + DD + ">");
  html = html.replace("<li", "<" + LI);
  html = html.replace("</li>", "</" + LI + ">");
  return html;
}

And then you can process your html string like

html = customizeListTags(html);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
  result = Html.fromHtml(html,Html.FROM_HTML_MODE_LEGACY, null, new CustomTagHandler());
} else {
  //noinspection deprecation
  result = Html.fromHtml(html, null, new CustomTagHandler());
}



回答2:


I've published a compatibility library to standardize and backport the Html class across Android versions which includes more callbacks for elements and styling:

https://github.com/Pixplicity/HtmlCompat

Specifically, given this invocation:

Spanned fromHtml = HtmlCompat.fromHtml(context, source, 0,
        imageGetter, tagHandler, spanCallback);

you will be interested in implementing TagHandler for unknown tags, and SpanCallback for customizing the Spans that HtmlCompat creates from HTML.



来源:https://stackoverflow.com/questions/38935756/html-tag-handler-not-called-in-android-n-for-ul-li

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!