最近公司项目有这么一个需求,展示文章内容后台返回给我们的是一个富文本格式的字符串 这个还是比较简单
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) } }
记录一下这个需求解决,以后直接拿来用