WebView页面加载进度的设计

发表于 2020-07-03
阅读 17

介绍

介绍

手机网络很不稳定,我们在使用WebView控件展示网页给用户的时候,如果网络慢,则用户长时间看到空白体验很不好

然后福哥就设计了一个页面加载进度提示,用户知道加载完成比例感觉会好很多

教程

设计布局

放一个 webView,再放一个 imageView,默认 imageView 是隐藏的

这样 imageView 就遮住了 webView

<WebView
    android:id="@+id/webview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:visibility="visible"/>
<ImageView
    android:id="@+id/loading"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:scaleType="center"
    android:visibility="gone"
    android:src="@mipmap/ic_launcher"/>

初始化

初始化 webView 和 imageView 控件

webView = findViewById(R.id.webview);
imgLoading = findViewById(R.id.loading);

imgLoading.setRotation(180f);

重载加载进度方法

我们重载 webChromeClient 对象的 onProgressChanged 方法

webChromeClient = new WebChromeClient(){

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
        if(newProgress < 100){
            imgLoading.setRotation(180*newProgress/100);
            imgLoading.setVisibility(View.VISIBLE);
        }
        else{
            imgLoading.setRotation(180f);
            imgLoading.setVisibility(View.GONE);
        }
    }
};

测试

我们启动程序会发现,默认有一个图片是倒着的

随着页面的加载,这个图片会自动旋转

页面加载完成的时候,这个图片就正过来了

鬼谷子叔叔

跟福哥学编程吧~~
日志
212
浏览
1626