1

我已经在 stackoverflow 中看到了一个类似的问题,但我想要一个更好地解释这个问题的答案。我是 android 开发的新手,我想弄清楚如何将我的 java 代码中的变量传递给 index.html 中的 javascript。欢迎任何建议。

4

2 回答 2

0

Try with the following code may be it will help you.

//Android WebView code
JavaScriptInterface JSInterface;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
wv = (WebView)findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
// register class containing methods to be exposed to JavaScript
JSInterface = new JavaScriptInterface();
wv.addJavascriptInterface(JSInterface, "JSInterface");
wv.loadUrl("file:///android_asset/myPage.html");
}

public class JavaScriptInterface {
@android.webkit.JavascriptInterface
public void showToast(String msg)
{
    Log.d("TAG",msg);
}
}



//This is your web page
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
       function init()
       {
          var testVal = 'Android Toast!’;
          Android.showToast(testVal);
       }
    </script>
</head>
<body>
<div style="clear: both;height: 3px;"> </div>
  <div>
  <input value="submit" type="button" name="submit"
       id="btnSubmit" onclick="javascript:return init();" />
</div>
 </body>
</html>
于 2021-06-30T07:10:30.627 回答
0

您可以尝试使用 JsBridge 库:

https://github.com/lzyzsd/JsBridge
于 2021-06-30T06:19:58.033 回答