我需要Android中的javascript'confirm(msg)'等功能。 类似于AlertDialog,但有可能返回值,而不是回调。 有没有办法实现这个?
UPDATE 这样的功能不适合我的问题:
builder.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
method1();
});
builder.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
method2();
});
我需要这样的东西:
if (confirmDialog.askConfirm()) {
method1();
} else {
method2();
}
答案 0 :(得分:0)
答案 1 :(得分:0)
我已经用这种方式解决了我的问题:
public class JSStyleConfirmDialog {
private volatile boolean interrupted = false;
private volatile boolean result;
private volatile boolean resultObtained = false;
public static final int YES = 1;
public static final int NO = 0;
public static final int ERROR = -1;
public int askConfirm(final ClientActivity activity, final String msg) {
Thread thread = new Thread() {
@Override
public void run() {
try {
while (!resultObtained) {
Thread.sleep(20);
}
} catch (InterruptedException e) {
interrupted = true;
}
}
};
thread.start();
new Handler(Looper.getMainLooper()).post(new Runnable() {
@Override
public void run() {
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(msg);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result = true;
resultObtained = true;
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result = false;
resultObtained = true;
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
try {
thread.join();
} catch (InterruptedException e) {
return ERROR;
}
if (interrupted) {
return ERROR;
}
return result?YES:NO;
}
}
必须从非ui线程调用:
int result = new JSStyleConfirmDialog().askConfirm(activity, msg);