接上一篇文章
上一篇文章我们只写了访问网络的情况,很简单,这里我们写访问本地的情况,打开本地网页分为两种情况,html代码和html文件
打开html代码
package com.example.webview;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
public class MainActivity extends Activity {
private WebView wv_WebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv_WebView = (WebView) findViewById(R.id.wb_webview);
String htmlCode="<html>" +
"<body>I am a student!</body>" +
"</html>";
wv_WebView.loadData(htmlCode, "text/html", null);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
运行结果:
但是一般情况下我们很少这么使用,我们都是打开html文件
我们看下我创建的html文件
<!DOCTYPE html>
<html>
<head>
<meta charset="GBK">
<title>Insert title here</title>
</head>
<body>
张欣为什么那么爱我
</body>
</html>
package com.example.webview;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.webkit.WebView;
public class MainActivity extends Activity {
private WebView wv_WebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wv_WebView = (WebView) findViewById(R.id.wb_webview);
//注意格式是固定的
wv_WebView.loadUrl("file:///android_asset/myhtml.html");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
“`
看下运行效果