Android 服务端返回的数据含有html字段时的解析方式

如果服务器端返回的数据结构中包含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%, 高度根据宽高比自动匹配, 基本上能解决所遇到的问题了

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值