一、创建一个HTML网址进行测试
webView.html
<html> <head> <title> </title> </head> <body> <input type="button" value="Say hello" onClick="showAndroidToast('Web传递参数到Android')" /> <script type="text/javascript"> function test(card_mo ,price){ Android.showtest(card_mo+price); } function showAndroidToast(toast) { Android.showToast(toast); } </script> </body> </html>
2.创建一个JavaScriptInterface 接口类
package com.ruidde.csndresourcedemo; import android.content.Context; import android.webkit.JavascriptInterface; import android.widget.Toast; /** * Created by Administrator on 2017/1/5. */ public class JavaScriptInterface { Context mContext; /** Instantiate the interface and set the context */ JavaScriptInterface(Context c) { mContext = c; } @JavascriptInterface /** Show a toast from the web page */ public void showToast(String toast) { Toast.makeText(mContext, toast+"0000000", Toast.LENGTH_SHORT).show(); } @JavascriptInterface /** Show a toast from the web page */ public void showtest(String toast) { Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show(); } }
3.在Activity中使用
package com.ruidde.csndresourcedemo; import android.os.Bundle; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { private String card_mo ,price ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); card_mo = "1234565"; price = "32.00"; WebView myWebView = (WebView) findViewById(R.id.webview); //设置js可用 WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); //注解自定义对象 js用自定义的对象如:Android 来调用Android中方法 myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android"); //网址本地自己写的 myWebView.loadUrl("file:///android_asset/webView.html"); //webView网页加载进度 myWebView.setWebChromeClient(new WebChromeClient() { @Override public void onProgressChanged(WebView view, int newProgress) { super.onProgressChanged(view, newProgress); if (newProgress == 100){ //网页加载完成 /** * //这是Android调用js的方法 如:test方法在js中要有(可以给js中传递参数) * 方法在web加载完成后 会调用下面方法来给js传递参数 * */ view.loadUrl("javascript:test('" + card_mo+ "','" + price+ "')"); //aa是js的函数test()的参数 } } } ); } }