javascript - 从 JavaScript 调用 Java 方法并将值返回给 JavaScript
问题描述
关于从 Javascript 调用 Java 类方法的 SO 问题和其他文章很少,但它们都处理带有返回类型的 java 方法void
。
这是我要实现的目标: WebView 中要显示 2 个字符串 - 说Yes和No。但是它们需要本地化,因此我想从 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"),
};
当我运行上面的代码时,我得到了空白字符串作为输出。
以下是一些注意事项:
- 如果我使用硬编码字符串,此 Javascript 将被适当使用,因为它可以工作
- 已在
string.xml
- 我尝试
calculatorjavascriptcallinterface
在骆驼大写和小写中都使用 - 我试过有没有
window.
调用Java方法 - 尝试从 Java 方法返回硬编码值 -它是这样工作的
任何建议将不胜感激。提前致谢!
编辑 即使字符串存在于strings.xml中,我也会收到以下错误:
No package identifier when getting value for resource number 0x00000000
android.content.res.Resources$NotFoundException: String resource ID #0x0
解决方案
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);
}
推荐阅读
- swift - SwiftUI Conditional List - Unable to infer complex closure return type
- python - emacs flycheck-mode python3 print 语句,文件=sys.stderr
- asp.net - 两个表之间的匹配记录
- python-3.x - 为什么 numpy.random.choice 会修改我的数据?
- r - 为什么我的孩子 Rmd 中的 include_graphics 不起作用?
- apache-kafka - 只读最新的 kafka 消息
- excel - 以编程方式将 XLSX 样式从一个文件复制到另一个文件
- spring-boot - 如何传递查询变量
- python - 在 iot edge 模块中传递环境变量
- gatsby - 对非博客内容的 Netlify CMS 感到困惑