[英]html converted bold or italic spanned string in android
我的自定義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
嘗試改變這些行
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.