WebView学习2

来源:互联网 发布:2017优化重组数学答案 编辑:程序博客网 时间:2024/06/01 09:38

说明:功能代码参考网上资料

转载:http://blog.csdn.net/wangtingshuai/article/details/8631835

布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <WebView        android:id="@+id/wv_webview"        android:layout_width="match_parent"        android:layout_height="300dp" >    </WebView>    <Button        android:layout_width="match_parent"        android:layout_height="40dp"        android:onClick="btClick"        android:text="JAVA调用JS方法" />    <EditText        android:id="@+id/et_text"        android:layout_width="match_parent"        android:layout_height="50dp" /></LinearLayout>

JAVA代码

package com.syswea.webview;import android.annotation.SuppressLint;import android.app.Activity;import android.os.Bundle;import android.view.View;import android.webkit.WebView;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;/** * 1、完成交互:JAVA调用JS中的方法 */@SuppressLint("JavascriptInterface")public class MainActivity02 extends Activity {private WebView webView;private EditText editText;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);editText = (EditText) findViewById(R.id.et_text);webView = (WebView) findViewById(R.id.wv_webview);WebViewSetting.setWebViewFunction(webView);// 加载本地文件webView.loadUrl("file:///android_asset/wst.html");}/** * JAVA调用JS方法 */public void btClick(View v) {startNoParameter();startParameter();}// 有参数调用private void startParameter() {String input = editText.getText().toString();input = "JAVA调用有参数的JS方法" + input;webView.loadUrl("javascript:javacalljswithargs('" + input + "')");}// 无参数调用private void startNoParameter() {webView.loadUrl("javascript:javacalljs()");}}

javascript代码:

<html><head><meta http-equiv="Content-Type"content="text/html;charset=gb2312"><script type="text/javascript">function javacalljs(){ document.getElementById("content").innerHTML +=            "<br\>java调用了js函数";}function javacalljswithargs(arg){ document.getElementById("content").innerHTML +=            ("<br\>"+arg);}</script></head><body>this is my html <br/><a onClick="window.wst.startFunction()">点击调用java代码</a><br/><a onClick="window.wst.startFunction('hello world')" >点击调用java代码并传递参数</a><br/><div id="content">内容显示</div></body></html>


0 0