如果WebView
中没有可用的连接页面/提醒,我就会做某事(例如加载本地html页面或提醒)。我要玩Prevent WebView from displaying "web page not available"但没有任何成功。任何建议将不胜感激。
答案 0 :(得分:5)
这一切都归结为只是从onReceivedError显示一个AlertDialog:
@Override
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
//Clearing the WebView
try {
webView.stopLoading();
} catch (Exception e) {
}
try {
webView.clearView();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
//Showing and creating an alet dialog
AlertDialog alertDialog = new AlertDialog.Builder(youractivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("No internet connection was found!");
alertDialog.setButton("Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
//Don't forget to call supper!
super.onReceivedError(webView, errorCode, description, failingUrl);
}
如果您是WebView的新手,您将会像这样实现onReceivedError:
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
//Code here
}
});
答案 1 :(得分:4)
上面的代码给了我两个弃用警告,所以我建议修改如下。这包含在包含WebView组件的活动中:
myWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Cannot connect to the R2R Server. Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
});
答案 2 :(得分:0)
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
// declare a text view in your xml
sample_TextView.setText(R.string.no_internet_connection);
view.loadUrl("about:blank");
}