dar*_*ius 5 java user-interface midlet java-me
我正在寻找一个简单的解决方案,用于在Java ME midlet中使用yes/no对话框.我想像这样使用它,但其他方式都很好.
if (YesNoDialog.ask("Are you sure?") == true) {
// yes was chosen
} else {
// no was chosen
}
Run Code Online (Sandbox Code Playgroud)
你需要一个警报:
警报是一个屏幕,向用户显示数据并等待一段时间后再继续显示下一个Displayable.警报可以包含文本字符串和图像.Alert的预期用途是告知用户错误和其他异常情况.
使用2个命令(在您的情况下为"是"/"否"):
如果警报中存在两个或多个命令,它将自动转换为模态警报,并且超时值始终为FOREVER.警报将保留在显示屏上,直到调用Command.
这些是MIDP 1.0及更高版本支持的内置类.您的代码段也永远不会有效.这样的API需要阻止等待用户选择和回答的调用线程.这恰好与MIDP的UI交互模型的方向相反,MIDP基于回调和委托.您需要提供自己的类,实现CommandListener,并为异步执行准备代码.
这是一个基于Alert的(未经测试的!)示例类:
public class MyPrompter implements CommandListener {
private Alert yesNoAlert;
private Command softKey1;
private Command softKey2;
private boolean status;
public MyPrompter() {
yesNoAlert = new Alert("Attention");
yesNoAlert.setString("Are you sure?");
softKey1 = new Command("No", Command.BACK, 1);
softKey2 = new Command("Yes", Command.OK, 1);
yesNoAlert.addCommand(softKey1);
yesNoAlert.addCommand(softKey2);
yesNoAlert.setCommandListener(this);
status = false;
}
public Displayable getDisplayable() {
return yesNoAlert;
}
public boolean getStatus() {
return status;
}
public void commandAction(Command c, Displayable d) {
status = c.getCommandType() == Command.OK;
// maybe do other stuff here. remember this is asynchronous
}
};
Run Code Online (Sandbox Code Playgroud)
使用它(再次,未经测试,在我的头顶):
MyPrompter prompt = new MyPrompter();
Display.getDisplay(YOUR_MIDLET_INSTANCE).setCurrent(prompt.getDisplayable());
Run Code Online (Sandbox Code Playgroud)
此代码将在应用程序中提示当前显示的表单,但不会像您发布的示例中那样阻止您的线程.您需要继续运行并等待commandAction调用.