当用户在webview android中按回键时停止页面重定向

时间:2015-02-26 07:48:42

标签: android webview

 public void onBackPressed (){
    WebView webview = (WebView) findViewById(R.id.mainWebView);
    if (webview.isFocused() && webview.canGoBack()) {
            webview.goBack();       
    }
    else {
            super.onBackPressed();
            finish();
    }
}
private class MyCustomWebViewClient extends WebViewClient {

    ProgressDialog progressDialog = new ProgressDialog(AndroidMobileAppSampleActivity.this);

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        progressDialog.setMessage("Processing");
        progressDialog.setCancelable(false);
        progressDialog.setOnKeyListener(new OnKeyListener(){
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                    KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                }
                else
                    return false;
            }});
        progressDialog.show();
    }


    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        progressDialog.setMessage("Processing");
        progressDialog.setCancelable(false);
        progressDialog.setOnKeyListener(new OnKeyListener(){
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode,
                    KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                }
                else
                    return false;
            }});
        progressDialog.show();
        view.loadUrl(url);
        return true;
    }

    public void onPageFinished(WebView view, String url) {
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }


}

这是我的代码,我在webview中加载一个url并在用户重定向到另一个页面时显示一个处理对话框,现在我想停止我的页面重定向,并在用户按下后退键时隐藏处理对话框。我尝试但没有成功,请帮忙。提前致谢

1 个答案:

答案 0 :(得分:0)

清除已完成页面加载的历史记录。 没有回溯史。

mWebView.setWebViewClient(new WebViewClient(){
    @Override
    public void onPageFinished(WebView view, String url) 
    {
        mWebView.clearHistory();
        super.onPageFinished(view, url);
    }
});