在真实的工程开发中,一个富文本编辑器,不是仅仅可以编辑显示,还需要处理富文本的转换与解析,方便传输与存储。一般来说,HTML文本是比较理想的网络传输格式。如何将安卓的span式富文本和HTML文本之间进行互转,是本篇介绍的重点。
首先,介绍富文本转成HTML。我们需要做的,是遍历文本中的span对象,并用合适的html标签来修饰span对象对应的文本。示例代码如下:
public static String convertSpannedToRichText(Spanned spanned) {
List spanList =
Arrays.asList(spanned.getSpans(0, spanned.length(), CharacterStyle.class));
SpannableStringBuilder stringBuilder = new SpannableStringBuilder(spanned);
for (CharacterStyle characterStyle : spanList) {
int start = stringBuilder.getSpanStart(characterStyle);
int end = stringBuilder.getSpanEnd(characterStyle);
if (start >= 0) {
String htmlStyle = handleCharacterStyle(characterStyle,
stringBuilder.subSequence(start, end).toString());
if (htmlStyle != null) {
stringBuilder.replace(start, end, htmlStyle);
}
}
}
return stringBuilder.toString();
}
private static String handleCharacterStyle(CharacterStyle characterStyle, String text) {
if (characterStyle instanceof BoldSpan) {
return String.format("%s", text);
} else if (characterStyle instanceof UrlSpan) {
UrlSpan span = (UrlSpan) characterStyle;
return String.format("