如果手机上没有数据连接,如何显示我的自定义 HTML 代码?
自定义 HTML 代码:
String customHtml = "<html><body>Hello, WebView</body></html>";
webView.loadData(customHtml, "text/html", "UTF-8");
这是我的完整代码:
package com.webbrowser.android;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://domain.com");
}
}
编辑:
这是正确的吗?它在模拟器上不起作用。请您再看一遍好吗?
编辑2:
添加了括号。
public class MainActivity extends Activity {
private WebView webView;
public boolean isConnected() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return (cm.getActiveNetworkInfo() != null &&
cm.getActiveNetworkInfo().isConnectedOrConnecting());
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
if(!isConnected()) {
String customHtml = "<html><body>Hello, WebView</body></html>";
webView.loadData(customHtml, "text/html", "UTF-8");
} else {
webView.loadUrl("http://domain.com");
}
}
}