WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
webView =(WebView)findViewById(R.id.webview);
WebSettings settings =webView.getSettings();
webView.requestFocusFromTouch();
settings.setJavaScriptEnabled(true); //支持js
settings.setAllowFileAccess(true); //设置可以访问文件
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//判断重定向的方式二
if (mIsPageLoading) {
return false;
}
if (url !=null && url.startsWith("http")) {
webView.loadUrl(url);
return true;
}else {
Uri uri = Uri.parse(url);
Intent intent =new Intent(Intent.ACTION_VIEW, uri);
try {
view.getContext().startActivity(intent);
}catch (ActivityNotFoundException e) {
e.printStackTrace();
}
return true;
}
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mIsPageLoading =true;
Log.d("---------", "onPageStarted");
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mIsPageLoading =false;
Log.d("---------", "onPageFinished");
}
});
}
private boolean mIsPageLoading;
/**
* 按键响应,在WebView中查看网页时,检查是否有可以前进的历史记录。
*/
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
if (webView.canGoBack()) {
webView.goBack();
return true;
}else {
finish();
}
}
return super.onKeyDown(keyCode, event);
}
activity_web.xml 文件
android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> android:layout_width="match_parent" android:layout_height="match_parent" android:layerType="none" >