Android:Html.toHtml()在每个单词上添加html标记

时间:2015-03-12 11:54:14

标签: java android html

Html.toHtml()分别对每个单词应用标签

原文: Hello World

Html.ToHtml()结果:

<p dir="ltr"><b>Hello</b><b> </b><b>World</b></p>

我想将所有重复的<b>标记合并到一个<b>标记中。

这是我用来应用span

的代码
spannable.setSpan(new StyleSpan(typeFace), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

将typeFace用于Typeface.BOLDTypeface.ITALIC

我也试过Spannable.SPAN_EXCLUSIVE_EXCLUSIVE,但仍然没用。

这是我在输入

时在EditText中应用span的方式
protected void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
    super.onTextChanged(text, start, lengthBefore, lengthAfter);
    if (lengthAfter > lengthBefore)
        applyCurrentStyle(start, start + lengthAfter);
}

applyCurrentStyle():

private void applyCurrentStyle(int startSpan, int endSpan) {
    for (Style style : mCurrentStyles) {
        boolean alreadyHas = false;
        switch (style) {
            case BOLD:
                for (StyleSpan span : getStyleSpans(Typeface.BOLD, startSpan, endSpan)) {
                    if (getText().getSpanEnd(span) == endSpan) {
                        alreadyHas = true;
                        break;
                    }
                }
                if (!alreadyHas)
                    setStyleSpan(Typeface.BOLD, startSpan, endSpan);
                break;
            case ITALIC:
                for (StyleSpan span : getStyleSpans(Typeface.ITALIC, startSpan, endSpan)) {
                    if (getText().getSpanEnd(span) == endSpan) {
                        alreadyHas = true;
                        break;
                    }
                }
                if (!alreadyHas)
                    setStyleSpan(Typeface.ITALIC, startSpan, endSpan);
                break;
        }
    }
}

0 个答案:

没有答案