您的位置:首页 > 移动开发 > Android开发

android和js互相调用

2016-05-26 21:29 330 查看
布局

<RelativeLayout 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"

>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:onClick="callJs"

android:id="@+id/button"

android:text="java调用js"

/>

<WebView

android:layout_width="match_parent"

android:layout_height="match_parent"

android:id="@+id/webView"

android:layout_below="@+id/button"

/>

</RelativeLayout>

=================================================================================

代码

package com.example.day_10_android_js;

import android.annotation.SuppressLint;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.webkit.JsResult;

import android.webkit.WebChromeClient;

import android.webkit.WebSettings;

import android.webkit.WebView;

import android.widget.Toast;

public class MainActivity extends Activity {

private WebView webView;

@SuppressLint("JavascriptInterface")

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

webView = (WebView) findViewById(R.id.webView);

webView.loadUrl("file:///android_asset/jstest.html");

WebSettings settings = webView.getSettings();

//webVIew是否支持js

settings.setJavaScriptEnabled(true);

webView.setWebChromeClient(new WebChromeClient(){

/* (non-Javadoc)

* @see android.webkit.WebChromeClient#onJsAlert(android.webkit.WebView, java.lang.String, java.lang.String, android.webkit.JsResult)

*/

@Override

public boolean onJsAlert(WebView view, String url, String message,

JsResult result) {

// TODO Auto-generated method stub

return super.onJsAlert(view, url, message, result);

}

});

//js调用java

//添加暴露给js的接口//参数一:object对象,实现要被js调用的方法;参数二:暴露给js的接口名

webView.addJavascriptInterface(new Object(){

@android.webkit.JavascriptInterface//4.0之后要加这个注解

public void toast(String str){

Toast.makeText(MainActivity.this, str, 0).show();

}

}, "jsCallJava");

}

//点击按钮,调用js方法

public void callJs(View v){

webView.loadUrl("javascript:testJavacallJs('"+"java传过来的"+"')");

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: