如何添加自定义 "webpage not available"
how to add custom "webpage not available"
我开发了一个 webview android 应用程序,当用户没有连接到网络时,应用程序当然会显示此页面 "webpage not available"
我需要添加自定义页面(自定义错误图像。
请帮帮我!
实现这个其实很简单:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new CustomWebViewClient());
webView.loadUrl("http://google.scom");
// Inserted an error in the URL to load to test the onErrorReceived.
// You could also just remove the internet connection or remove the internet permission.
}
class CustomWebViewClient extends WebViewClient {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
view.loadData("<html>OMG! SOMETHING WENT WRONG!</html>", "", "");
}
}
}
这个想法是您提供自己的 WebViewClient
自定义实现。在此 class (CustomWebViewClient
) 中,您覆盖了 onReceivedError
方法,每当将 URL 加载到 WebView
失败时调用该方法。我根本没看过 errorCode
,但你可以用它来区分不同的错误。
然后当加载失败时,您只需将静态 HTML 页面加载到您的 Webview
中。我不建议从互联网上加载另一个 URL,因为这可能会以无限循环结束,因为在互联网连接不可用时会一遍又一遍地调用此方法。
我开发了一个 webview android 应用程序,当用户没有连接到网络时,应用程序当然会显示此页面 "webpage not available" 我需要添加自定义页面(自定义错误图像。
请帮帮我!
实现这个其实很简单:
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new CustomWebViewClient());
webView.loadUrl("http://google.scom");
// Inserted an error in the URL to load to test the onErrorReceived.
// You could also just remove the internet connection or remove the internet permission.
}
class CustomWebViewClient extends WebViewClient {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
view.loadData("<html>OMG! SOMETHING WENT WRONG!</html>", "", "");
}
}
}
这个想法是您提供自己的 WebViewClient
自定义实现。在此 class (CustomWebViewClient
) 中,您覆盖了 onReceivedError
方法,每当将 URL 加载到 WebView
失败时调用该方法。我根本没看过 errorCode
,但你可以用它来区分不同的错误。
然后当加载失败时,您只需将静态 HTML 页面加载到您的 Webview
中。我不建议从互联网上加载另一个 URL,因为这可能会以无限循环结束,因为在互联网连接不可用时会一遍又一遍地调用此方法。