android和js互相调用

布局

<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传过来的"+"')");

}



}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值