WebView中ProgressDialog设为setCancelable(false)后返回键失效求助
问题
在WebView中使用设置了setCancelable(false)的ProgressDialog时,按下返回键既无法返回上一页面,也无法关闭该ProgressDialog。期望实现:ProgressDialog保持setCancelable(false)状态,按下返回键时关闭它并回到上一Activity。
原代码
progressDialog = new ProgressDialog(this); progressDialog.setMessage("Loading..."); progressDialog.setCancelable(false); progressDialog.show(); // Start timeout runnable after 3 seconds handler = new Handler(); timeoutRunnable = new Runnable() { @Override public void run() { // Change the text of the ProgressDialog progressDialog.setMessage("Taking longer to load..."); } }; handler.postDelayed(timeoutRunnable, 3000); // 3 seconds delay // Load the webpage in WebView webView.loadUrl("https://www.example.com"); } private class CustomWebViewClient extends WebViewClient { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); // Cancel the timeout runnable when the page is finished loading handler.removeCallbacks(timeoutRunnable); // Dismiss the ProgressDialog if (progressDialog.isShowing()) { progressDialog.dismiss(); } } @Override public void onBackPressed() { isBackPressed = true; if (progressDialog.isShowing()) { progressDialog.dismiss(); } }
解决方案
问题根源
你把onBackPressed()方法写在了CustomWebViewClient类内部,而onBackPressed()是Activity的生命周期方法,放在WebViewClient中不会被系统触发,所以完全无效。另外,即使方法位置正确,原逻辑也只关闭了对话框,没有执行返回上一Activity的操作。
修正步骤
- 将
onBackPressed()方法移到你的Activity类中,而非WebViewClient内部 - 修改方法逻辑,确保关闭对话框后调用
super.onBackPressed()完成返回操作
修正后的onBackPressed()代码:
@Override public void onBackPressed() { // 检查对话框是否显示 if (progressDialog != null && progressDialog.isShowing()) { progressDialog.dismiss(); // 关闭对话框后,执行返回上一Activity的操作 super.onBackPressed(); } else { // 无对话框时,优先让WebView回退页面,否则返回上一Activity if (webView.canGoBack()) { webView.goBack(); } else { super.onBackPressed(); } } }
- 确保WebView已设置自定义WebViewClient(如果之前没加):
webView.setWebViewClient(new CustomWebViewClient());
说明
- 保持
progressDialog.setCancelable(false)可以防止用户点击对话框外部关闭它 - 通过重写Activity的
onBackPressed(),手动拦截返回键事件,既实现关闭对话框,又完成返回上一Activity的需求
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

