Reputation: 183
I have method in my custom EditText that makes the text bold or italic
here is my method:
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;
}
}
When i switch bold text style to italic style or inverse every thing is fine and in the EditText it change from bold to italic but when i want to convert that text to html the problem comes and returns an html that contains both html tags bolded italic text but i want just switch between bold or italic.
here is my converting to html method:
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();
}
in a short way
i want this:
This is <b>simple</b> text
or
This is <i>simple</i> text
but the output is this:
This is <b><i>simple</i></b> text
Upvotes: 0
Views: 456
Reputation:
try to change these lines
SpannableString span = new SpannableString(getText().subSequence(startSelection, endSelection));
span.setSpan(new StyleSpan(Typeface.NORMAL), 0, span.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
to
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);
Upvotes: 0