html在android中转换为粗体或斜体的字符串

时间:2018-07-13 11:49:54

标签: android android-edittext spannablestring spannablestringbuilder

我的自定义EditText中有一个方法,使文本粗体斜体

这是我的方法:

public boolean changeTextStyle(TextStyle style) {
    if (isTextSelected()) {
        int startSelection = getSelectionStart();
        int endSelection = getSelectionEnd();
        SpannableString span = new SpannableString(getText().subSequence(startSelection, endSelection));
        span.setSpan(new StyleSpan(Typeface.NORMAL), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        span.setSpan(new CustomTypefaceSpan(getTypeface()), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        switch (style) {
            case BOLD_STYLE: {
                span.setSpan(new StyleSpan(Typeface.BOLD), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            break;
            case ITALIC_STYLE: {
                span.setSpan(new StyleSpan(Typeface.ITALIC), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            break;
        }
        getText().replace(startSelection, endSelection, span);
        setSelection(endSelection);
        return true;
    } else {
        return false;
    }
}

当我将粗体文本样式切换为斜体样式或反之时,一切都很好,并且在EditText中,它从粗体更改为斜体,但是当我想将该文本转换时到html的问题来了,并返回了一个包含两个html标签的html粗体斜体文本,但是我只想在粗体或斜体之间切换。

这是我转换为html方法:

public String getFinalText() {
    return StringEscapeUtils.unescapeHtml4(Html.toHtml(getText())
            .replace("<p dir=\"ltr\">", "")
            .replace("<p dir=\"rtl\">", "")
            .replace("<u>", "")
            .replace("</u>", "")
            .replace("<p>", "")
            .replace("</p>", ""))
            .trim();
}

简而言之

我想要这个:

This is <b>simple</b> text

This is <i>simple</i> text

但是输出是这样的:

This is <b><i>simple</i></b> text

1 个答案:

答案 0 :(得分:0)

尝试更改这些行

SpannableString span = new SpannableString(getText().subSequence(startSelection, endSelection));
        span.setSpan(new StyleSpan(Typeface.NORMAL), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

SpannableString span = new SpannableString(getText().subSequence(startSelection, endSelection));
final StyleSpan[] spans = span.getSpans(0, span.length(), StyleSpan.class);
for (StyleSpan styleSpan : spans) span.removeSpan(styleSpan);