首页 > 解决方案 > 从 JavaScript 调用 Java 方法并将值返回给 JavaScript

问题描述

关于从 Javascript 调用 Java 类方法的 SO 问题和其他文章很少,但它们都处理带有返回类型的 java 方法void

这是我要实现的目标: WebView 中要显示 2 个字符串 - 说YesNo。但是它们需要本地化,因此我想从 Java 方法中获取字符串值,而不是为每个语言环境使用多个 JS。

这是代码示例: Java 类

onCreate(){
//Some code
contentWebView.addJavascriptInterface(new CalculatorJavaScriptCallInterface(), "calculatorjavascriptcallinterface");
//Some code
}

String localizedString = "";
private class CalculatorJavaScriptCallInterface {
    CalculatorJavaScriptCallInterface() {
    }

    @JavascriptInterface
    public String getLocalizedString(final int stringId) {
        localizedString = getResources().getString(stringId);
        Toast.makeText(getActivity(), "localizedString :: " + localizedString, Toast.LENGTH_SHORT).show();

        return localizedString;
    }
}

Javascript 文件

  function Checkboxpicker(element, options) {
    //Some code
    this.options = $.extend({}, $.fn.checkboxpicker.defaults, options, this.$element.data());
}
  $.fn.checkboxpicker.defaults = {
    //EXISTING STRINGS
    //offLabel: 'No',
    //onLabel: 'Yes',
    offLabel: window.calculatorjavascriptcallinterface.getLocalizedString("Consult.JSSupport.checkbox.selected"),
    onLabel: window.calculatorjavascriptcallinterface.getLocalizedString("Consult.JSSupport.checkbox.notSelected"),
  };

当我运行上面的代码时,我得到了空白字符串作为输出。

以下是一些注意事项:

  1. 如果我使用硬编码字符串,此 Javascript 将被适当使用,因为它可以工作
  2. 已在 string.xml
  3. 我尝试calculatorjavascriptcallinterface在骆驼大写和小写中都使用
  4. 我试过有没有window. 调用Java方法
  5. 尝试从 Java 方法返回硬编码值 -它是这样工作的

任何建议将不胜感激。提前致谢!


编辑 即使字符串存在于strings.xml中,我也会收到以下错误:

No package identifier when getting value for resource number 0x00000000
android.content.res.Resources$NotFoundException: String resource ID #0x0

标签: javascriptandroidandroid-webview

解决方案


1.)

 mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.addJavascriptInterface(new WebViewInterface(this), "Android");
    mWebView.loadUrl("url or html file path");

2.)

public class WebViewInterface {

    Context mContext;

    WebViewInterface(Context mContext) {
        this.mContext = mContext;
    }

    @JavascriptInterface
    public void performAction(String pro_cat_id) {
          //write your code here to perform any action.
    }

3.)

 <html>
    <head>
        <script type="text/javascript" src="/js/MyJS.js"></script>
    </head>
    <body>
        <button onClick="mClick('1');">Yes</button>
        <button onClick="mClick('0');">No</button>
    </body>
</html>

4.) javascript: MyJS.js

function mClick(mValue)
{
    Android.performAction(mId);
}

推荐阅读