Android提供了WebView控件展示web页面的能力,还可通过WebViewClient类辅助WebView处理各种通知、请求。
核心代码:
mWebView = (WebView) findViewById(R.id.WebView);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.baidu.com");
Activity文件
package com.app.myweb;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
/**
* WebView控件
* @author 402-9
*/
public class WebViewTest extends Activity{
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);//设置使用够执行JS脚本
webView.getSettings().setBuiltInZoomControls(true);//设置使支持缩放
// webView.getSettings().setDefaultFontSize(5);
webView.loadUrl("http://10.0.2.2:8888/csdn/");
webView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);// 使用当前WebView处理跳转
return true;//true表示此事件在此处被处理,不需要再广播
}
@Override //转向错误时的处理
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
Toast.makeText(WebViewTest.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
}
@Override //默认点回退键,会退出Activity,需监听按键操作,使回退在WebView内发生
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
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/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>