Android WebView的一个简单demo。
最终效果图:
AndroidManifest.xml中加访问INTERNET权限
<uses-permission android:name="android.permission.INTERNET"/>
MainActivity
package com.example.shen.webviewdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
String url = "http://bbs.meitiandian.com/plugin.php?id=wechat:access";
webView = (WebView) findViewById(R.id.webview);
//启用支持JavaScript
webView.getSettings().setJavaScriptEnabled(true);
//启用支持DOM Storage
webView.getSettings().setDomStorageEnabled(true);
//加载web资源
webView.loadUrl(url);
//覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为,使网页用WebView打开
webView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
//改写物理按键的返回的逻辑
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();//返回上一页面
return true;
} else {
finish();
}
}
return super.onKeyDown(keyCode, event);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#0F0">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="WebViewDemo"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp"/>
</RelativeLayout>
<WebView
android:id="@+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/hello_world" />
</LinearLayout>
demo下载地址:
http://download.youkuaiyun.com/download/shenyuanqing/9177165