webview的简单实例

package com.delightPress.chap61;

import android.app.Activity;

import android.content.Context;

import android.os.Bundle;

import android.os.Handler;

import android.webkit.WebView;

import android.widget.Toast;

/**

 * 新增一个Activity,使用web1里的WebView并且指到一个自定义的网页

 */

public class WebOne extends Activity {

/**

* Javascript的响应对象,成员函数就是可以调用的接口

*/

public class JScriptInterface{

Context m_context;

JScriptInterface(){

m_context = WebOne.this;

}

/**

* 运行函数产生一个Toast对象在Activity之下

*/

public void showToast(String toast){

Toast.makeText(m_context, toast, Toast.LENGTH_SHORT).show();

}

}

@Override

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setContentView(R.layout.web2);

WebView myWebView = (WebView) findViewById(R.id.webview);

//自定义的网页中用loadUrl来指定网址

myWebView.loadUrl("http://www.agogoapp.com/android/sample1.html");

WebView myWebView2 = (WebView) findViewById(R.id.webview2);

//自定义的网页中用loadUrl来指定网址

//myWebView2.loadUrl("http://www.agogoapp.com/android/sample2.html");

myWebView2.loadUrl("file:///android_asset/demo.html");

//允许网页组件执行javascript并且设置javascript执行的界面

myWebView2.getSettings().setJavaScriptEnabled(true);

myWebView2.addJavascriptInterface(new JScriptInterface(), "ALibro");

}

}

 
demo.html在asset目录下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<title>WebView page with Javascript enabled</title>
<script type="text/javascript">
    function showAndroidToast(toast) {
        window.ALibro.showToast(toast);
    }
</script>
</head>
<body>
<input type="button" value="Button1"
onclick="showAndroidToast('Show Toast Button1')" />
<input type="button" value="Button2"
onclick="showAndroidToast('Show Toast Button2')" />
 
</body>
</html>
 
权限:
<uses-permission android:name="android.permission.INTERNET"/>
原文地址:https://www.cnblogs.com/xingmeng/p/2458938.html