Android TagHandler does not affect standard tags

I use TextView to display an HTML string, for example:

"Test HTML <a href = \" www.type1.com \ "> link1 </a> <a href = \" www.type2.com \ "> link2 </a>"

As you can see, there are two different types of tags that I need to process, so I need to be able to process two different types of tags and read the href attribute.

I tried using Html.TagHandler:

private class MyTagHandler implements Html.TagHandler { @Override public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) { Toast.makeText(getContext(), tag, Toast.LENGTH_LONG).show(); } } 

However, handleTag is not called on <a>. I did tests and found out that this only affects the configured tags. Can stardard tags also be processed?

+6
source share
1 answer

The goal of the custom implementation of Html.TagHandler is to enable the processing of tags that are not processed by the Android framework. Therefore, in order to do what you want, one way is to replace all the tags that you want to process with another tag that, as you know, the framework will not process, so it will go into your implementation. For example, you can make a method like this to prepare html:

 public string prepareHTMLForTagHandling(string htmlSource) { if (htmlSource == null || htmlSource == "") return null; return htmlSource.replace("<a", "<acustomlink") .replace("</a>", "<acustomlink>"); } 

And then use it like:

 Html.fromHtml(prepareHTMLForTagHandling(myHtml), null, myHtmlCustomTagHandler); 

Finally, in your custom tag handler implementation, you are processing "acustomlink" as a tag instead of "a".

Hope this helps.

+1
source

All Articles