Last active
November 30, 2023 00:20
-
-
Save mrmike/77fe2a6a357e78108115 to your computer and use it in GitHub Desktop.
Remove extra space from Android spannable
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void setText(String html) { | |
SpannableStringBuilder spanned = (SpannableStringBuilder) Html.fromHtml(html); | |
spanned = trimSpannable(spanned); | |
mTextView.setText(spanned, TextView.BufferType.SPANNABLE); | |
} | |
private SpannableStringBuilder trimSpannable(SpannableStringBuilder spannable) { | |
checkNotNull(spannable); | |
int trimStart = 0; | |
int trimEnd = 0; | |
String text = spannable.toString(); | |
while (text.length() > 0 && text.startsWith("\n")) { | |
text = text.substring(1); | |
trimStart += 1; | |
} | |
while (text.length() > 0 && text.endsWith("\n")) { | |
text = text.substring(0, text.length() - 1); | |
trimEnd += 1; | |
} | |
return spannable.delete(0, trimStart).delete(spannable.length() - trimEnd, spannable.length()); | |
} |
Doesn't that have a problem when it deletes from front and from the end?
spannable.length()
will still have the old value when the new one is actually shorter already from having removed from the start.
Works perfectly...
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks.. its is awsom'