需求:webview内容超过400就显示点击展开,点击收起功能
关键代码:
rich_desc_web?.setWebViewClient(object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
// 使用当前WebView处理跳转
view.loadUrl(url)
// true表示此事件在此处被处理,不需要再广播
return true
}
override fun onReceivedError(view: WebView, request: WebResourceRequest, error: WebResourceError) {
super.onReceivedError(view, request, error)
}
override fun onPageFinished(view: WebView, url: String) {
super.onPageFinished(view, url)
LogUtil.i("onPageFinished","onPageFinished")
Handler().postDelayed(Runnable { //int contentHeight = view.getContentHeight();
val viewHeight = view.height
LogUtil.i("onPageFinished",viewHeight.toString()+"\t")
richHeight = viewHeight
if (richHeight > 400){
setRichHeight(400)
tv_rich_show_all?.visibility = View.VISIBLE
} else {
setRichHeight(richHeight)
}
LogUtil.i("onPageFinished","onPageFinished1")
}, 500)
}
})
onPageFinished页面加载完,加下延迟确保拿到webview真实高度。注意其他富文本控件获取可能为0,请使用webview控件。
点击展开控件代码:
tv_rich_show_all?.setOnClickListener {
if (tv_rich_show_all?.text.toString() == "点击展开"){
setRichHeight(richHeight)
tv_rich_show_all?.text = "点击收起"
tv_rich_show_all?.setCompoundDrawablesWithIntrinsicBounds(null,null,resources.getDrawable(R.mipmap.icon_celebrity_close),null)
} else {
setRichHeight(400)
tv_rich_show_all?.text = "点击展开"
tv_rich_show_all?.setCompoundDrawablesWithIntrinsicBounds(null,null,resources.getDrawable(R.mipmap.icon_celebrity_open),null)
}
}
private fun setRichHeight(height:Int){
//至于是否是LinearLayout.LayoutParams看你WebView外层控件是什么
val richParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,height)
richParams.leftMargin = UtilHelper.dip2px(mActivity,10f)
richParams.rightMargin = UtilHelper.dip2px(mActivity,10f)
rich_desc_web?.layoutParams = richParams
}
关键:在onPageFinished获取WebView高度处理逻辑
题外话:如果不想看到刚进去折叠的过程,可在WebView上面加多一层加载的loading布局,等WebView折叠完,再隐藏loading布局即可。
解决问题的请点个赞
网友评论