在Android中有类似javascript'confirm(msg)'的东西吗?

时间:2017-07-23 07:11:44

标签: javascript android alertdialog confirm

我需要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();
}

2 个答案:

答案 0 :(得分:0)

非常确定这是您正在寻找的: https://developer.android.com/guide/topics/ui/dialogs.html

答案 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);