前言:
Android中WebView的坑很多,比如低版本内核不支持,加载速度慢,重定向等等,当使用ScrollView嵌套WebView时坑更多,有人说为啥要嵌套?单独使用WebView或者ScrollView不行吗?答案是当然不行,需求就是如此,页面涉及的内容比较多,一个ScrollView显示不完,怎么实现产品和经理不会管的,反正开发要解决,当然这里没有引战的意思,也不是吐槽,只是纯粹讨论技术.
1.关于网上在ScrollView嵌套WebView时有几种常规的解决方案:
Mobile mobile = new Mobile();addJavascriptInterface(mobile, "mobile");
private class Mobile {@JavascriptInterfacepublic void onGetWebContentHeight() {//重新调整webview高度X5WebView.this.post(() -> {X5WebView.this.measure(0, 0);int measuredHeight = X5WebView.this.getMeasuredHeight();ViewGroup.LayoutParams layoutParams = X5WebView.this.getLayoutParams();layoutParams.height = measuredHeight;X5WebView.this.setLayoutParams(layoutParams);}); } }
2.实现的效果图如下:
3.这样设置后发现并没有什么卵用,换第2种:
@JavascriptInterface public void resize(final float height) {((Activity) getContext()).runOnUiThread(new Runnable() {@Overridepublic void run() {X5WebView.this.setLayoutParams(new LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, (int) (height * getResources().getDisplayMetrics().density)));}}); }
4.这种方法也没有什么用,有的文章说是前端H5也要写该方法,不知道是不是此原因.实现的效果图如下:
5.还有一种方法是在Stack Overflow上找的,虽然解决了留白问题,但是宽度又没有显示完整,最后放弃了。
6.终极大法:自定义WebView,在onMeause重新测量高度。
/*** @作者: njb* @时间: 2019/12/4 12:55* @描述: 自定义WebView适配不同手机高度*/ @SuppressLint("NewApi") public class CustomNestedScrollWebView extends WebView {public CustomNestedScrollWebView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {super(context, attrs, defStyleAttr, defStyleRes);} public CustomNestedScrollWebView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);} public CustomNestedScrollWebView(Context context, AttributeSet attrs) {super(context, attrs);} public CustomNestedScrollWebView(Context context) {super(context);} @Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {//根据手机屏幕重新计算高度int mExpandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST);super.onMeasure(widthMeasureSpec, mExpandSpec);} }
7.最后给出运行成功的截图如下:这里我跑的是模拟器,项目中跑了各种真机小米、华为、魅族、锤子等等,都正常显示.
8.至此,ScrollView嵌套Webview底部留白问题得以真正解决.
最后小伙伴们如有更好的方法可以给我留言,如有问题,欢迎提出,我及时更改。谢谢大家
9.项目demo源码地址:
X5WebViewDemo: 腾讯X5内核使用实例