android webview显示富文本 并获取里面的图片地址 点击图片查看大图

最近公司项目有这么一个需求,展示文章内容后台返回给我们的是一个富文本格式的字符串 这个还是比较简单

webview.loadDataWithBaseURL(null, url, "text/html", "UTF-8", null)

但是返回的url里面的图片地址需要我们自己再拼接一下公司的图片http地址上去,在网上找了个方法

private fun getImgStr(html: String): String{
    var new_html = html
    var img = ""
    var p_image: Pattern
    var m_image: Matcher
    val regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>"
    p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE)
    m_image = p_image.matcher(html)
    while (m_image.find()){
        img = m_image.group()
        val m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img)
        while (m.find()){
            获取到的img标签的src图片地址
            val result = m.group(1)
            Logger.d(result)
            //然后根据需求替换为新的图片地址
            when (result.contains("http")){
                true -> new_html = new_html.replace(result, result)
                false -> new_html = new_html.replace(result, Api.BASEPIC + result)
            }

        }
    }
    //把新的富文本展示出来
    return new_html
}

webview图片都能正常的展示出来了,然后又有新的需求提出需要点击图片查看图片大图,网上找了方法

val javaScriptInterface = MyJavaInterface(this)
webview.addJavascriptInterface(javaScriptInterface, "imagelistner")
webview.webViewClient = object : WebViewClient(){
    override fun onPageFinished(view: WebView?, url: String?) {
        super.onPageFinished(view, url)
        setWebImageClick(view!!, "imagelistner")
    }

    override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
        view?.settings?.javaScriptEnabled = true
        super.onPageStarted(view, url, favicon)
    }
}
/**
 * 设置网页中图片的点击事件
 * @param view
 *
 */
fun setWebImageClick(view: WebView, method: String) {
    var jsCode="javascript:(function(){" +
            "var imgs=document.getElementsByTagName(\"img\");" +
            "for(var i=0;i<imgs.length;i++){" +
            "imgs[i].pos = i;"+
            "imgs[i].οnclick=function(){" +
            "window."+method+".openImage(this.src,this.pos);" +
            "}}})()"
    view.loadUrl(jsCode)
}
class MyJavaInterface(val context: Context) {

    @JavascriptInterface
    fun content(message: String) {

    }

    @JavascriptInterface
    fun pay(num: Int) {

    }
    @JavascriptInterface
    fun openImage(img: String, pos: Int){
        FullImageActivity.startFullImageActivity(context, img)
    }
}

记录一下这个需求解决,以后直接拿来用

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值