Skip to content

Instantly share code, notes, and snippets.

@venator85
Created January 15, 2020 11:02
Show Gist options
  • Save venator85/920158bdf4ec89eca3bbac8d0ab0890f to your computer and use it in GitHub Desktop.
Save venator85/920158bdf4ec89eca3bbac8d0ab0890f to your computer and use it in GitHub Desktop.
A Html.fromHtml() TagHandler to support <del> on Android <= 6
import android.text.Editable;
import android.text.Html;
import android.text.Spannable;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;
import org.xml.sax.XMLReader;
public class DelTagHandler implements Html.TagHandler {
public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
if (opening) {
handleStartTag(tag, output);
} else {
handleEndTag(tag, output);
}
}
private void handleStartTag(String tag, Editable output) {
if (tag.equalsIgnoreCase("del")) {
start(output, new Strikethrough());
} else if (tag.equalsIgnoreCase("s")) {
start(output, new Strikethrough());
} else if (tag.equalsIgnoreCase("strike")) {
start(output, new Strikethrough());
}
}
private void handleEndTag(String tag, Editable output) {
if (tag.equalsIgnoreCase("del")) {
end(output, Strikethrough.class, new StrikethroughSpan());
} else if (tag.equalsIgnoreCase("s")) {
end(output, Strikethrough.class, new StrikethroughSpan());
} else if (tag.equalsIgnoreCase("strike")) {
end(output, Strikethrough.class, new StrikethroughSpan());
}
}
private void start(Editable text, Object mark) {
int len = text.length();
text.setSpan(mark, len, len, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
}
private void end(Editable text, Class kind, Object repl) {
Object obj = getLast(text, kind);
if (obj != null) {
setSpanFromMark(text, obj, repl);
}
}
private <T> T getLast(Spanned text, Class<T> kind) {
/*
* This knows that the last returned object from getSpans()
* will be the most recently added.
*/
T[] objs = text.getSpans(0, text.length(), kind);
if (objs.length == 0) {
return null;
} else {
return objs[objs.length - 1];
}
}
private void setSpanFromMark(Spannable text, Object mark, Object... spans) {
int where = text.getSpanStart(mark);
text.removeSpan(mark);
int len = text.length();
if (where != len) {
for (Object span : spans) {
text.setSpan(span, where, len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
private static class Strikethrough {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment