views:

135

answers:

1

Dear people,

I am trying to build an android application for a message board. To display formatted html for the post contents I have chosen the TextView and the Html.fromHtml() method. That, unfortunately, covers only a few html tags. The unknown tags are handled by a class that implements TagHandler and has to be generated by myself.

Now, I googled a lot and can't find an example of how this class should work. Let's consider I have an u tag for underlining some text (I know that this is deprecated, but whatever). How does my TagHandler look like?

It is called in the following way:

public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {

The first two arguments are fine. I guess I have to modify output using output.append(). But how do I attach something underlined there?

Best regards and thanks in advance, Jan Oliver

A: 

So, i finally figured it out by myself.

public class MyHtmlTagHandler implements TagHandler {

    public void handleTag(boolean opening, String tag, Editable output,
            XMLReader xmlReader) {
        if(tag.equalsIgnoreCase("strike") || tag.equals("s")) {
            processStrike(opening, output);
        }
    }

    private void processStrike(boolean opening, Editable output) {
        int len = output.length();
        if(opening) {
            output.setSpan(new StrikethroughSpan(), len, len, Spannable.SPAN_MARK_MARK);
        } else {
            Object obj = getLast(output, StrikethroughSpan.class);
            int where = output.getSpanStart(obj);

            output.removeSpan(obj);

            if (where != len) {
                output.setSpan(new StrikethroughSpan(), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }

    private Object getLast(Editable text, Class kind) {
        Object[] objs = text.getSpans(0, text.length(), kind);

        if (objs.length == 0) {
            return null;
        } else {
            for(int i = objs.length;i>0;i--) {
                if(text.getSpanFlags(objs[i-1]) == Spannable.SPAN_MARK_MARK) {
                    return objs[i-1];
                }
            }
            return null;
        }
    }


}

if anybody needs it.

Cheers

janoliver