ProgressBar与WebView加载进度的同步

发布时间:2024-08-16 16:25:28 作者:小樊
来源:亿速云 阅读:80

ProgressBar和WebView加载进度的同步可以通过监听WebView的加载状态来实现。

首先,在布局文件中添加一个ProgressBar和一个WebView:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ProgressBar
        android:id="@+id/progress_bar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

然后在Activity中找到WebView和ProgressBar,并为WebView设置一个WebViewClient,并重写其onProgressChanged方法:

public class MainActivity extends AppCompatActivity {

    private WebView webView;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = findViewById(R.id.webview);
        progressBar = findViewById(R.id.progress_bar);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                progressBar.setProgress(newProgress);
                if (newProgress == 100) {
                    progressBar.setVisibility(View.GONE);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                }
            }
        });

        webView.loadUrl("https://www.example.com");
    }
}

在上面的代码中,我们重写了WebViewClient的onProgressChanged方法,当WebView加载进度发生变化时,我们将ProgressBar的进度设置为当前进度,并根据进度值来显示或隐藏ProgressBar。当加载完成时,将ProgressBar隐藏起来。

这样就实现了ProgressBar和WebView加载进度的同步。

推荐阅读:
  1. ProgressBar如何优化界面加载体验
  2. SeekBar在视频编辑中的精准定位策略

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

progressbar

上一篇:SeekBar在音频波形显示中的应用

下一篇:环形ProgressBar的进度反馈方式

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》