在主布局上设置进度对话框

时间:2015-05-16 10:46:14

标签: android android-webview progressdialog

我有一个代码,其中进度对话框与主布局一起出现。我希望进度对话框位于前端,主要布局在后台,就像显示链接enter link description here一样。

public class MainActivity extends Activity {
    private WebView webView;
    private EditText urlEditText;
    private ProgressBar progress;

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

        urlEditText = (EditText) findViewById(R.id.urlField);
        webView = (WebView) findViewById(R.id.webView);
        webView.setWebViewClient(new MyWebViewClient());

        progress = (ProgressBar) findViewById(R.id.progressBar);
        progress.setVisibility(View.GONE);
        Button openUrl = (Button) findViewById(R.id.goButton);
        openUrl.setOnClickListener(new OnClickListener() {

            @SuppressLint("SetJavaScriptEnabled")
            @Override
            public void onClick(View view) {
                String url = urlEditText.getText().toString();
                if (validateUrl(url)) {
                    webView.getSettings().setJavaScriptEnabled(true);
                    webView.loadUrl(url);

                }
            }

            private boolean validateUrl(String url) {
                return true;
            }
        });

    }

    private class MyWebViewClient extends WebViewClient {   
         @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }

         @Override
        public void onPageFinished(WebView view, String url) {
             progress.setVisibility(View.GONE);
                MainActivity.this.progress.setProgress(100);
            super.onPageFinished(view, url);
        }

         @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
             progress.setVisibility(View.VISIBLE);
            MainActivity.this.progress.setProgress(0);
            super.onPageStarted(view, url, favicon);
        }
    }

    public void setValue(int progress) {
        this.progress.setProgress(progress);        
    }
} 

1 个答案:

答案 0 :(得分:0)

尝试使用WebChromeClient而不是WebViewClient来显示和更新进度:

在调用webview.loadUrl()之前显示pregress栏:

if (validateUrl(url)) {
    webView.getSettings().setJavaScriptEnabled(true);
    progress.setVisibility(View.VISIBLE);
    webView.loadUrl(url);
}

更新onProgressChanged的进度:

webView.setWebChromeClient(new WebChromeClient() {
     @Override
     public void onProgressChanged(WebView view, int newProgress) {
        super.onProgressChanged(view, newProgress);
        if (newProgress == 100) {
            progress.setVisibility(View.GONE);
        } else {
            progress.setProgress(newProgress);
        }
     }
});