如果服务器端返回的数据结构中包含html类型字段, 通常在客户端有两种控件来渲染
第一个就是TextView
通常HTML字段还包含Img标签, 处理方式为
/**
* html标签的字符串转换
*/
public void htmlWebPic(final String htmlContent) {
Thread t = new Thread(new Runnable() {
Message msg = mHandler.obtainMessage();
@Override
public void run() {
Html.ImageGetter imageGetter = source -> {
URL url;
Drawable drawable = null;
try {
url = new URL(source);
drawable = Drawable.createFromStream(
url.openStream(), null);
drawable.setBounds(0, 0, 800, 465); // 宽800像素, 高465像素
} catch (Exception e) {
e.printStackTrace();
}
return drawable;
};
CharSequence result;
if (htmlContent.contains("http://120.76.74.105:8085")) {
result = Html.fromHtml(htmlContent, imageGetter, null);
} else {
String replace = htmlContent.replace("/upload/", ServiceConfig.BASE_URL + "upload/");
result = Html.fromHtml(replace, imageGetter, null);
}
msg.what = 0x12;
msg.obj = result;
mHandler.sendMessage(msg);
}
});
t.start();
}
回到主线程进行UI操作
private Handler mHandler = new Handler(new Handler.Callback() {
public boolean handleMessage(Message msg) {
if (msg.what == 0x12) {
mTextView.setText((CharSequence) msg.obj);
}
return false;
}
});
第二种方式直接使用WebView
调用API就好了
String htmlContent;
mWebView.loadDataWithBaseURL(ServiceConfig.BASEURL, htmlContent, "text/html", "utf-8", null);
如果出现WebView加载图片显示不正常,不能很好的适配屏幕,可以这样解决
htmlContent= htmlContent.replace("<img", "<img style='max-width:90%;height:auto;'");
字符串替换掉原来的Img标签, 控制图片的宽度在屏幕的90%, 高度根据宽高比自动匹配, 基本上能解决所遇到的问题了