Html.toHtml()不会转换RelativeSizeSpan的ed文本

时间:2013-09-19 15:53:37

标签: android html spannable

这是我想要做的,

    SpannableString s = new SpannableString("Shiva");
    s.setSpan(new RelativeSizeSpan(2f), 0, 5, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    editText.setText(s, TextView.BufferType.SPANNABLE);

在Click事件上,我试图通过此代码将其转换为HTML

    Log.d("SampleApp",Html.toHtml(editText.getText()));

我期待一些

 <h1> or <h2> tag

但我看到的是这个

<p dir=ltr>Shiva</p>

如果可以,请帮助我。

2 个答案:

答案 0 :(得分:0)

Html.toHtml将返回<p><div>标记中的内容,

你看过Html.toHtml的源代码吗?

检查以下代码,我从最新的Android 4.3版本中提取了该代码。 你可以看到toHtml函数调用inHtml和withinHtml函数只需将div放在span周围并设置align属性。

public static String toHtml(Spanned text) {
        StringBuilder out = new StringBuilder();
        withinHtml(out, text);
        return out.toString();
    } 

private static void withinHtml(StringBuilder out, Spanned text) {
        int len = text.length();

        int next;
        for (int i = 0; i < text.length(); i = next) {
            next = text.nextSpanTransition(i, len, ParagraphStyle.class);
            ParagraphStyle[] style = text.getSpans(i, next, ParagraphStyle.class);
            String elements = " ";
            boolean needDiv = false;

            for(int j = 0; j < style.length; j++) {
                if (style[j] instanceof AlignmentSpan) {
                    Layout.Alignment align =
                        ((AlignmentSpan) style[j]).getAlignment();
                    needDiv = true;
                    if (align == Layout.Alignment.ALIGN_CENTER) {
                        elements = "align=\"center\" " + elements;
                    } else if (align == Layout.Alignment.ALIGN_OPPOSITE) {
                        elements = "align=\"right\" " + elements;
                    } else {
                        elements = "align=\"left\" " + elements;
                    }
                }
            }
            if (needDiv) {
                out.append("<div ").append(elements).append(">");
            }

            withinDiv(out, text, i, next);

            if (needDiv) {
                out.append("</div>");
            }
        }
    }

答案 1 :(得分:0)

另一种方法是使用AbsoluteSizeSpan.class
s.setSpan(new AbsoluteSizeSpan(14),0,5,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
这会返回类似于:&lt; font size =&#34; 2&#34;&gt; Shiva&lt; / font&gt;