I've a TextView that will receive some html formatted text like:
<p class="p1"><span class="s1"><strong>Name</strong> Mr. A</span></p>
<p class="p1"><span class="s1"><strong>Place:</strong> Somewhere over the rainbow...</span></p>
I'm using this code:
CharSequence sequence = Html.fromHtml(html);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
text.setText(strBuilder);
Ended up with:
Name: Mr. A\n\nPlace: Somewhere over the rainbow\n\n
Problem, I don't want "\n\n" I just want one "\n", so I've done this:
sequence = sequence.toString().replaceAll("\n\n", "\n");
Ended up with:
Name: Mr. A\nPlace: Somewhere over the rainbow\n
And to remove the last "\n":
try {
int i = sequence.toString().lastIndexOf("\n");
sequence = new StringBuilder(sequence).replace(i, i + 1, "").toString();
} catch (Exception e) {
e.printStackTrace();
}
Ended up with:
Name: Mr. A\nPlace: Somewhere over the rainbow
Perfect just like I wanted, but now all the HTML format is gone.
How can I solve this situation?
Thanks.
EDIT 1:
User Bas van Stein suggested I should remove StringBuilder, but I didn't post all the code. So, I use a StringBuilder because if the text contains an URL I do something like this (complete code):
CharSequence sequence = Html.fromHtml(html);
sequence = sequence.toString().replaceAll("\n\n", "\n");
try {
int i = sequence.toString().lastIndexOf("\n");
sequence = new StringBuilder(sequence).replace(i, i + 1, "").toString();
} catch (Exception e) {
e.printStackTrace();
}
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
URLSpan[] urls = strBuilder.getSpans(0, sequence.length(), URLSpan.class);
for (URLSpan span : urls) {
makeLinkClickable(context, strBuilder, span, color);
}
text.setText(strBuilder);
makeLinkClickable method:
private void makeLinkClickable(final Context context, SpannableStringBuilder strBuilder, final URLSpan span, int color) {
int start = strBuilder.getSpanStart(span);
int end = strBuilder.getSpanEnd(span);
int flags = strBuilder.getSpanFlags(span);
strBuilder.setSpan(new ClickableSpan() {
@Override
public void onClick(View widget) {
...
}
}, start, end, flags);
strBuilder.setSpan(new ForegroundColorSpan(color), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
strBuilder.removeSpan(span);
}
EDIT 2:
Ok so I figured out what is causing the loss of the format information, is the fact that I'm ignoring the Spanned text converted from Html.fromHtml(html). I guess I'll have to remove the "\n\n" and the last "\n" without losing the Spanned object with all the Span styles, etc. Working on it...
<br/>to replace\n. Since you want HTML line breaks, in HTML code - not Java ones.