Android开发之WebView加载HTML源码包含转义字符实现富文本显示的方法
生活随笔
收集整理的這篇文章主要介紹了
Android开发之WebView加载HTML源码包含转义字符实现富文本显示的方法
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
老套路先看效果圖:
WebView加載帶有轉移字符的HTML源碼
再看轉義后的字符的效果圖:
先看WebView加載HTML源碼的方法如下:
webview.loadDataWithBaseURL(null, html源碼, "text/html", "utf-8", null);如上圖如果HTML中帶有轉義字符加載出來就會跟第一張效果圖一樣,這樣需要我們手動轉義一下。目前有兩種方法
方法一:可將轉義字符替換下:(不推薦因為HTML的轉義字符太多了)
htmlData = htmlData.replaceAll("&", ""); htmlData = htmlData.replaceAll(""", "\""); htmlData = htmlData.replaceAll("<", "<"); htmlData = htmlData.replaceAll(">", ">"); htmlData = htmlData.replaceAll("nbsp;", " ");方法二:(極力推薦)
方法二經本人多次測試如果進行圖文混排文字和圖片在同一行不換行可能出現圖片無法顯示出來
if (!TextUtils.isEmpty(htmlData)) {Spanned spanned = null;if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {//使用HTML的方法轉義,api24以上方法spanned = Html.fromHtml(htmlData, Html.FROM_HTML_MODE_COMPACT);} else {//使用HTML的方法轉義,api24以下方法spanned = Html.fromHtml(htmlData);}MCLog.e("打印HTML源碼", spanned.toString());wvReadMsgContent.loadDataWithBaseURL(null, spanned.toString(), "text/html", "utf-8", null);//數據加載后隱藏縮放按鈕wvReadMsgContent.getSettings().setDisplayZoomControls(false);}如果看著亂我貼下源碼:ReadMessageActivity.java
package com.mchsdk.paysdk.activity;import android.os.Bundle; import android.text.Html; import android.text.Spanned; import android.view.View; import android.view.WindowManager; import android.webkit.WebView; import android.widget.ImageView; import android.widget.TextView;import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.RequestParams; import com.mchsdk.paysdk.bean.DeleteMsgBean; import com.mchsdk.paysdk.bean.GotMsgByIdParam; import com.mchsdk.paysdk.bean.MsgContentBean; import com.mchsdk.paysdk.callback.YhshNetRequestCallBack; import com.mchsdk.paysdk.config.MCHConstant; import com.mchsdk.paysdk.utils.MCLog; import com.mchsdk.paysdk.utils.TextUtils; import com.mchsdk.paysdk.utils.YhshNetUtils; import com.mchsdk.paysdk.utils.YhshUtils; import com.xigu.gson.Gson;import org.apache.http.entity.StringEntity;import java.io.UnsupportedEncodingException;/*** 消息閱讀頁面** @author xiayiye5* 2020年6月5日16:49:56*/ public class ReadMessageActivity extends MCBaseActivity implements View.OnClickListener {private TextView tvReadMsgTitle;private TextView tvReadMsgTime;private WebView wvReadMsgContent;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED);setContentView(getLayout("activity_read_message"));initView();initData();}private void initView() {ImageView ivCloseReadMsg = findViewById(getId("iv_close_read_msg"));tvReadMsgTitle = findViewById(getId("tv_read_msg_title"));tvReadMsgTime = findViewById(getId("tv_read_msg_time"));wvReadMsgContent = findViewById(getId("wv_read_msg_content"));//設置網頁自適應wvReadMsgContent.getSettings().setUseWideViewPort(true);wvReadMsgContent.getSettings().setLoadWithOverviewMode(true);//設置網頁字體大小 // wvReadMsgContent.getSettings().setTextSize(WebSettings.TextSize.LARGEST);wvReadMsgContent.getSettings().setTextZoom(250);// 設置可以支持縮放wvReadMsgContent.getSettings().setSupportZoom(true);// 設置出現縮放工具wvReadMsgContent.getSettings().setBuiltInZoomControls(true);ivCloseReadMsg.setOnClickListener(this);}@Overridepublic void onClick(View v) {if (v.getId() == getId("iv_close_read_msg")) {finish();}}/*** 1.調用消息讀取成功,2.調用獲取消息內容*/private void initData() {int msgId = getIntent().getIntExtra("msgId", 0);RequestParams params = new RequestParams();GotMsgByIdParam gotMsgByIdParam = new GotMsgByIdParam();GotMsgByIdParam.BodyBean bodyBean = new GotMsgByIdParam.BodyBean();bodyBean.setId(msgId);gotMsgByIdParam.setBody(bodyBean);GotMsgByIdParam.HeaderBean headerBean = new GotMsgByIdParam.HeaderBean();headerBean.setToken(YhshUtils.getInstance().getLoginToken(this));gotMsgByIdParam.setHeader(headerBean);String json = new Gson().toJson(gotMsgByIdParam);MCLog.e("消息內容的參數", json);try {params.setBodyEntity(new StringEntity(json, "UTF-8"));} catch (UnsupportedEncodingException e) {e.printStackTrace();}params.setContentType("application/json");YhshNetUtils.getInstance().requestHttpPost(MCHConstant.DDD_URL_PRD + "gfanmsg/read", params, new MessageContentCallBack(1));YhshNetUtils.getInstance().requestHttpPost(MCHConstant.DDD_URL_PRD + "gfanmsg/info", params, new MessageContentCallBack(2));}class MessageContentCallBack implements YhshNetRequestCallBack {private int requestType;MessageContentCallBack(int requestType) {this.requestType = requestType;}@Overridepublic void onSuccess(String responseInfo) {if (requestType == 1) {MCLog.e("打印已讀消息數據", responseInfo + "");DeleteMsgBean deleteMsgBean = new Gson().fromJson(responseInfo, DeleteMsgBean.class);int result = deleteMsgBean.getResult();if (result == 1) {//已閱讀MCLog.e("閱讀", "閱讀成功!");}} else {MsgContentBean msgContentBean = new Gson().fromJson(responseInfo, MsgContentBean.class);MCLog.e("打印消息詳情數據", responseInfo);//設置消息內容updateMsgContentData(msgContentBean);}}@Overridepublic void onFail(HttpException e, String s) {String localizedMessage = e.getLocalizedMessage();MCLog.e("打印異常", localizedMessage + ":" + s);}}private void updateMsgContentData(MsgContentBean msgContentBean) {MsgContentBean.ResultBean resultContent = msgContentBean.getResult();if (resultContent != null) {String htmlData = resultContent.getMessage_text();tvReadMsgTitle.setText(resultContent.getMessage_title());tvReadMsgTime.setText(resultContent.getSend_time());if (!TextUtils.isEmpty(htmlData)) {Spanned spanned = null;if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {//使用HTML的方法轉義,api24以上方法spanned = Html.fromHtml(htmlData, Html.FROM_HTML_MODE_COMPACT);} else {//使用HTML的方法轉義,api24以下方法spanned = Html.fromHtml(htmlData);}MCLog.e("打印HTML源碼", spanned.toString()); // htmlData = htmlData.replaceAll("&", ""); // htmlData = htmlData.replaceAll(""", "\""); // htmlData = htmlData.replaceAll("<", "<"); // htmlData = htmlData.replaceAll(">", ">"); // htmlData = htmlData.replaceAll("nbsp;", " ");wvReadMsgContent.loadDataWithBaseURL(null, spanned.toString(), "text/html", "utf-8", null);//數據加載后隱藏縮放按鈕wvReadMsgContent.getSettings().setDisplayZoomControls(false);}}} }再看下xml布局:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><Viewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="3.7" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="32dp"android:layout_marginRight="32dp"android:background="@drawable/mch_input_back_shape"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"android:paddingTop="15dp"><TextViewandroid:layout_width="0dp"android:layout_height="wrap_content"android:layout_marginLeft="30dp"android:layout_weight="1"android:gravity="center"android:text="消息"android:textColor="@color/login_text"android:textSize="18sp" /><ImageViewandroid:id="@+id/iv_close_read_msg"android:layout_width="15dp"android:layout_height="15dp"android:layout_gravity="right"android:layout_marginRight="15dp"android:src="@drawable/mch_close1" /></LinearLayout><Viewandroid:layout_width="match_parent"android:layout_height="0.5dp"android:layout_marginTop="5dp"android:background="#DEDEDE" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:layout_marginLeft="2dp"android:layout_marginRight="2dp"android:background="@null"android:orientation="vertical"><TextViewandroid:id="@+id/tv_read_msg_title"android:layout_width="match_parent"android:layout_height="22dp"android:layout_marginLeft="15dp"android:layout_marginTop="5dp"android:layout_marginRight="15dp"android:gravity="center"android:singleLine="true"android:textColor="@color/login_text"android:textSize="15sp"tools:text="我是消息標題呀我是消息標題" /><TextViewandroid:id="@+id/tv_read_msg_time"android:layout_width="match_parent"android:layout_height="15dp"android:layout_marginLeft="15dp"android:layout_marginTop="5dp"android:layout_marginRight="15dp"android:layout_marginBottom="10dp"android:gravity="center"android:textColor="@color/login_text"android:textSize="11sp"tools:text="2019-05-03 10:59:51" /><WebViewandroid:id="@+id/wv_read_msg_content"android:layout_width="match_parent"android:layout_height="300dp"android:layout_marginBottom="17dp"android:scrollbars="none" /></LinearLayout></LinearLayout><Viewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_weight="4" /> </LinearLayout>代碼中缺少的圖片背景顏色請自行補全謝謝
總結
以上是生活随笔為你收集整理的Android开发之WebView加载HTML源码包含转义字符实现富文本显示的方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android开发之设置DialogFr
- 下一篇: 埃及胡夫金字塔内发现新通道:位于“巨大神