1. 程式人生 > >android中html和text互轉

android中html和text互轉

  1. 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));
  1. 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樣式的文字內容,文字中有&nbsp 字樣空格 瀏覽器識別不了 需如下替換

mHtml = mHtml.replaceAll(" ", " ");