android String与HTML的相互转换

1、保存TextView时将String值保存成HTML

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static String parseStringToHtml(String value)
  {
    if (TextUtils.isEmpty(value))
      {
        return value;
      }
    //注意"&"一定要放在第一个,要不然会把后面的<给去掉&
    value = value.replaceAll("&", "&amp;").replaceAll(" "," ");//&\空格
    value = value.replaceAll(""", "&quot;").replaceAll("'","&#039;");//双引号、单引号
    value = value.replaceAll("/", "&#039;").replaceAll(""", "&#034;");
    value = value.replaceAll("<", "<").replaceAll(">",">");
    value = value.replaceAll("\n", "<br/>");
    return value;
  }

2、显示时,需要将String换HTML显示出来

1
2
3
4
5
6
7
8
String content = workRecordBean.getWork_connect();
if (!TextUtils.isEmpty(content))
  {
    workContentView.setText(Html.fromHtml(content));
  } else
  {
    workContentView.setText(content);
  }

参考资料:

https://tool.lu/htmlentity/