//声明WebView对象
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//隐藏标题栏
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//隐藏状态栏
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//实例化webView(网络视图)对象
webView = new WebView(this);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.web_view);
webView.setWebViewClient(new WebViewClient(){});
//设置webView属性,能够执行Javascript代码
webView.getSettings().setJavaScriptEnabled(true);
WebSettings settings = webView.getSettings();
//设定支持viewport
settings.setUseWideViewPort(true);
//打开页面时,自适应屏幕
settings.setLoadWithOverviewMode(true);
//设定支持缩放
settings.setSupportZoom(true);
settings.setBuiltInZoomControls(true);
//默认缩放尺寸
settings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
//隐藏缩放图标
settings.setDisplayZoomControls(false);
//优先使用缓存
settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
//根据传入的参数再去加载新的网页
view.loadUrl(url);
//表示当前WebView可以处理打开新网页的请求,不用借助系统浏览器
return true;
}
});
//加载需要显示的页面(互联网)
webView.loadUrl("http://www.5mcn.cn");
//加载需要显示的页面(本地assets文件夹下)
// webView.loadUrl("file:///android_asset/test1.html");
}
@Override
/**
* 设置回退,返回上个页面而不是直接退出
* 覆盖Activity类的onKeyDown(int keyCoder,KeyEvent event)方法
*/
public boolean onKeyDown(int keyCode, KeyEvent event) {
if((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()){
webView.goBack();
return true;
}
else{
return super.onKeyDown(keyCode, event);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<WebView
android:id="@+id/web_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>