溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ProgressBar與WebView加載進度的同步

發(fā)布時間:2024-08-16 16:25:28 來源:億速云 閱讀:80 作者:小樊 欄目:移動開發(fā)

ProgressBar和WebView加載進度的同步可以通過監(jiān)聽WebView的加載狀態(tài)來實現(xiàn)。

首先,在布局文件中添加一個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設(shè)置一個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方法,當(dāng)WebView加載進度發(fā)生變化時,我們將ProgressBar的進度設(shè)置為當(dāng)前進度,并根據(jù)進度值來顯示或隱藏ProgressBar。當(dāng)加載完成時,將ProgressBar隱藏起來。

這樣就實現(xiàn)了ProgressBar和WebView加載進度的同步。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI