我是 Android 开发新手,我需要实现类似于ChildBrowser 插件中的自定义对话框插件。
虽然我已经设法实现了此对话框的大部分功能,包括某些对话框操作的 JS 回调事件,但我无法实现在对话框显示时将数据从 JS 发送回对话框。
场景如下:当对话框的 Spinner 发生变化时,正在调用 JS 回调,JS 代码执行一些处理(访问 sqlStorage 数据等),然后我需要更新对话框的一些视图。我当前的代码(没有不相关的东西):
CustomDialogPlugin.java:
public class CustomDialogPlugin extends Plugin {
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("show")) {
result = this.showDialog(args.optJSONObject(0), callbackId);
// ...
} else if (action.equals("update")) {
this.updateData(args.optJSONObject(0));
}
} catch(JSONException e) {
// ...
}
}
// Show the dialog
public String showDialog(JSONObject options, final String callbackId) {
if (options != null) {
// Handle options
}
// Create the child dialog in new thread
Runnable runnable = new Runnable() {
public void run() {
mDialog = new Dialog(ctx);
// Dialog layouts, views and listeners setup
// ...
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
// ...
// Prepare JSON data to send and call a callback
sendUpdate(CHANGED_EVENT, obj, true);
}
@Override
public void onNothingSelected(AdapterView adapter) {
// ...
}
});
// ...
mDialog.show();
}
};
this.ctx.runOnUiThread(runnable);
return "";
}
// Create a new plugin result and send it back to JavaScript
private void sendUpdate(int eventType, JSONObject obj, boolean keepCallback) {
if (this.savedCallbackId != null) {
// ...
PluginResult result = new PluginResult(PluginResult.Status.OK, obj);
Result.setKeepCallback(keepCallback);
this.success(result, this.savedCallbackId);
}
}
// Parse data received from JS and upate dialog
protected String updateData(JSONObject data) {
// Here I need to update some views of mDialog
// Can't access them from here
}
}
自定义对话框.js:
var CustomDialog = function() {};
CustomDialog.CHANGED_EVENT = 1;
CustomDialog.prototype.show = function(data) {
return PhoneGap.exec(this._onEvent, this._onError, 'CustomDialogPlugin', 'show', [data]);
};
CustomDialog.prototype.update = function(data) {
return PhoneGap.exec(this._onEvent, this._onError, 'CustomDialogPlugin', 'update', [data]);
};
CustomDialog.prototype._onEvent = function(data) {
if (data.type == CustomDialog.CHANGED_EVENT && typeof window.plugins.CustomDialog.onChange === "function") {
window.plugins.CustomDialog.onChange(data);
}
// ...
};
CustomDialog.prototype._onError = function(data) {
// ...
};
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin('customDialog', new CustomDialog());
});
测试.html:
// ...
window.plugins.customDialog.onChange = function(data) {
// ...
window.plugins.customDialog.update(some_other_data);
}
我试图创建一个Handler
inside Runnable
,并调用它来处理从 发送的消息updateData
,但显然我做错了什么。
也许我把事情复杂化了,有一种更简单的方法可以从 JS 回调中完成数据更新?
先感谢您。