Android的:如何使用Html.TagHandler?如何使用、Android、TagHandler、Html

2023-09-12 01:26:38 作者:可惜卟是迩ヽ陪ωǒ到最后

我想建立一个Android应用程序的留言板。要为我选择了TextView的和Html.fromHtml()方法后内容显示格式的HTML。 ,不幸的是,仅覆盖少数html标记。未知标签由实现TagHandler和必须由自己产生的类处理。

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.

现在,我用Google搜索了很多,找不到这个类应该如何工作的一个例子。让我们考虑一下我有下划线一些文字(我知道这是pcated德$ P $,但不管)使用u标签。怎么我的TagHandler样子?

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?

有被称为以下列方式:

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

前两个参数都很好。我想我必须使用output.append修改输出()。但我怎么附上一些强调呢?

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

推荐答案

所以,我终于理解了它由我自己。

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;
        }
    }


}

如果有人需要它。

干杯