0

我的自定义 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
4

1 回答 1

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);
于 2018-07-13T13:33:32.580 回答