- html转text
mEditText = (EditText) findViewById(R.id.et);
mEditText.setText(Html.fromHtml(content));
mTv_one = (TextView) findViewById(R.id.tv_one);
mTv_one.setText(Html.fromHtml(content));
- text转html
mTextView = (TextView) findViewById(R.id.tv);
String content=mEditText.getText().toString();
SpannableString spanString= newSpannableString(content);
String html=Html.toHtml(spanString);
String html_string=parseUnicodeToStr(html);
mTextView.setText(html_string);
用到的方法:
Html.toHtml()这个方法会将EditText里面的中文编码为Unicode十进制码,web浏览器能够正常识别,但是如果在非浏览器中显示的话就存在问题了。在Html.toHtml()转码后,通过正则将转码之后的Unicode再次转为String;
//unicode转String
public String parseUnicodeToStr(String unicodeStr) {
String regExp = "&#\\d*;";
Matcher m = Pattern.compile(regExp).matcher(unicodeStr);
StringBuffer sb = new StringBuffer();
while (m.find()) {
String s = m.group(0);
s = s.replaceAll("(&#)|;", "");
char c = (char) Integer.parseInt(s);
m.appendReplacement(sb, Character.toString(c));
}
m.appendTail(sb);
return sb.toString();
}
注意事项:如果上传html样式的文本内容,文本中有  字样空格 浏览器识别不了 需如下替换
mHtml = mHtml.replaceAll(" ", " ");