Android确认对话框返回true或false

Android确认对话框返回true或false,android,dialog,confirmation,Android,Dialog,Confirmation,似乎没有简单的方法可以让警报对话框返回简单的值。 此代码不起作用(无法从侦听器中设置应答变量,事实上它甚至不编译) 公共静态布尔确认(上下文){ 布尔答案; AlertDialog=新建AlertDialog.Builder(context.create(); 对话框。设置标题(“确认”); 设置消息(“选择是或否”); 对话框。可设置可取消(false); dialog.setButton(DialogInterface.BUTTON_“是”,新的DialogInterface.OnClick

似乎没有简单的方法可以让警报对话框返回简单的值。
此代码不起作用(无法从侦听器中设置应答变量,事实上它甚至不编译)

公共静态布尔确认(上下文){
布尔答案;
AlertDialog=新建AlertDialog.Builder(context.create();
对话框。设置标题(“确认”);
设置消息(“选择是或否”);
对话框。可设置可取消(false);
dialog.setButton(DialogInterface.BUTTON_“是”,新的DialogInterface.OnClickListener(){
public void onClick(对话框接口对话框,int按钮){
答案=正确;
}
});
dialog.setButton(DialogInterface.BUTTON_否定,“否”,新的DialogInterface.OnClickListener(){
public void onClick(对话框接口对话框,int按钮){
答案=错误;
}
});
setIcon(android.R.drawable.ic_对话框_警报);
dialog.show();
返回答案;
}
注意:方法必须是自包含的,也就是说,它不依赖于它外部的变量或构造。只要打电话就可以得到你的答案,对还是错

那么,该怎么办?返回的简单愿望似乎比它应得的复杂得多

此外,setButton方法具有以下形式:

dialog.setButton(int-buttonId,String-buttonText,Message-msg)

但不清楚如何使用它,会议发送到哪里,给谁,使用了哪个处理程序?

在活动中声明一个字段“应答”,并为其设置一个值。类的字段对于内部类是可见的,因此您可以这样做。

您可以为您的警报对话框创建一个侦听器,该侦听器使用接口侦听AlertDialogs操作

public class MyInterface {

    DialogReturn dialogReturn;

    public interface DialogReturn {

        void onDialogCompleted(boolean answer);
    }

    public void setListener(DialogReturn dialogReturn) {
        this.dialogReturn = dialogReturn;
    }

    public DialogReturn getListener() {
        return dialogReturn;

    }
}
创建一个接口

public class MyInterface {

    DialogReturn dialogReturn;

    public interface DialogReturn {

        void onDialogCompleted(boolean answer);
    }

    public void setListener(DialogReturn dialogReturn) {
        this.dialogReturn = dialogReturn;
    }

    public DialogReturn getListener() {
        return dialogReturn;

    }
}
现在,在您的类中,只需实现您使用
implements MyInterface.DialogReturn

然后您可以设置侦听器并使其工作,如下所示

public class Main extends Activity implements MyInterface.DialogReturn{

    MyInterface myInterface;
    MyInterface.DialogReturn dialogReturn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                ....
        myInterface = new MyInterface();
        myInterface.setListener(this);
    }


   public void Confirm(Context context) {
        AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setTitle("Confirmation");
        dialog.setMessage("Choose Yes or No");
        dialog.setCancelable(false);
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int buttonId) {
                myInterface.getListener().onDialogCompleted(true);
            }
        });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int buttonId) {
                myInterface.getListener().onDialogCompleted(false);
            }
        });
        dialog.setIcon(android.R.drawable.ic_dialog_alert);
        dialog.show();
         }


@Override
    public void onDialogCompleted(boolean answer) {
        Toast.makeText(Main.this, answer+"", Toast.LENGTH_LONG).show();
            if(answer)
            // do something
            else
            // do something
    }
}

嗯,我想说我对自己很满意,因为我找到了一个简单的答案,全靠我自己
但事实是,尽管我找到了一种返回值的方法(如下所示)这没有用

真正的问题是我需要一个同步对话框,一个在
Dialog.show()之后等待用户回答然后再恢复代码的对话框
Android中没有这样的野兽。所有对话框都是异步的,因此
dialog.show()
只在某个队列中发布对话框(我想)并继续。因此你没有及时得到答案

在下面的所有内容中,您将了解如何在构建对话框的方法中设置值。也许这种技术还有其他用途,与对话框生命周期无关




为了提供一些相关信息,我会说如果你更换

boolean答案;

最终布尔答案;
可以从侦听器中访问变量,但无法为其分配新值,因为它被声明为final

诀窍来了。
将变量定义为:

final boolean[]answer=新的boolean[1];
你们中的一些人已经明白了为什么这会起作用。这里的最后一个变量不是布尔数组的单个元素,而是数组本身。
因此,现在可以根据需要分配数组元素[0]

dialog.setButton(DialogInterface.BUTTON_“是”,新的DialogInterface.OnClickListener(){
public void onClick(对话框接口对话框,int按钮){
答案[0]=正确;
}
});
. . .
返回答案[0];

最后你可以从你的方法中返回它。

我在这个论坛上有类似的问题,但最后我得到了我的答案。 我在那篇文章中遇到的问题是如何创建单独的确认对话框类,该类可以被其他类或活动访问,因此使用该确认对话框类,我们不需要编写长代码

这是我的答案

首先,必须创建DialogHandler.java

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import src.app.R;

public class DialogHandler {
    public Runnable ans_true = null;
    public Runnable ans_false = null;

    // Dialog. --------------------------------------------------------------

    public boolean Confirm(Activity act, String Title, String ConfirmText,
            String CancelBtn, String OkBtn, Runnable aProcedure, Runnable bProcedure) {
        ans_true = aProcedure;
        ans_false= bProcedure;
        AlertDialog dialog = new AlertDialog.Builder(act).create();
        dialog.setTitle(Title);
        dialog.setMessage(ConfirmText);
        dialog.setCancelable(false);
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, OkBtn,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int buttonId) {
                         ans_true.run();
                    }
                });
        dialog.setButton(DialogInterface.BUTTON_NEGATIVE, CancelBtn,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int buttonId) {
                        ans_false.run();
                    }
                });
        dialog.setIcon(android.R.drawable.ic_dialog_alert);
        dialog.show();
        return true;
    }
}
这是在另一个类中调用它的示例

public class YourActivity extends Activity {
    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewById(R.id.button1).setOnClickListener(myclick);
    }

    public final Button.OnClickListener myclick = new Button.OnClickListener() {
        @Override
        public void onClick(View v) {
            doclick();
        }
    };

    public void doclick() {
        DialogHandler appdialog = new DialogHandler();
        appdialog.Confirm(this, "Message title", "Message content",
                "Cancel", "OK", aproc(), bproc());
    }

    public Runnable aproc(){
        return new Runnable() {
            public void run() {
                Log.d("Test", "This from A proc");
            }
          };
    }

    public Runnable bproc(){
        return new Runnable() {
            public void run() {
                Log.d("Test", "This from B proc");
            }
          };
    }


}

我还努力使用阻塞确认对话框,最后我使用了阻塞队列:

public static class BlockingConfirmDialog{

    private Activity context;

    BlockingQueue<Boolean> blockingQueue;

    public BlockingConfirmDialog(Activity activity) {
        super();
        this.context = activity;
        blockingQueue = new ArrayBlockingQueue<Boolean>(1);
    }

    public boolean confirm(final String title, final String message){

        context.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                new AlertDialog.Builder(context)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) { 
                        blockingQueue.add(true);
                    }
                 })
                 .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        blockingQueue.add(false);
                    }
                })
                 .show();
            }
        });

        try {
            return blockingQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }

    }
}
公共静态类阻塞确认对话框{
私人活动语境;
阻塞队列阻塞队列;
公共封锁确认对话框(活动){
超级();
这个上下文=活动;
blockingQueue=new ArrayBlockingQueue(1);
}
公共布尔值确认(最终字符串标题、最终字符串消息){
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
新建AlertDialog.Builder(上下文)
.setTitle(标题)
.setMessage(消息)
.setPositiveButton(“确定”,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int其中){
blockingQueue.add(true);
}
})
.setNegativeButton(“取消”,新建DialogInterface.OnClickListener()){
@凌驾
public void onClick(DialogInterface dialog,int which){
blockingQueue.add(false);
}
})
.show();
}
});
试一试{
return blockingQueue.take();
}捕捉(中断异常e){
e、 printStackTrace();
返回false;
}
}
}
我发现,在需要等待输入的情况下,使用它会有所帮助

它本质上等同于使用一个接口,但您可以创建完成和失败处理程序。这只是一个可以考虑的替代方案:

new ConfirmationDialog(mContext)
        .showConfirmation("Are you sure?", "Yes", "No")
        .done(new DoneCallback<Void>() {
            @Override
            public void onDone(Void aVoid) {
                ....
            }
        })
        .fail(new FailCallback<Void>() {

            @Override
            public void onFail(Void aVoid) {
                ...
            }
        });
新建确认对话框(mContext)
.showConfirmation(“您确定吗?”
    //this method displays a confirm dialog. If 'yes' answer, runs 'yesTask', 
    //if 'no' answer, runs 'noTask'
    //notice than 'yesTask' and 'noTask' are AysncTask
    //'noTask' can be null, example: if you want to cancel when 'no answer'

    public static void confirm(Activity act, String title, String confirmText,
                       String noButtonText, String yesButtonText,
                       final AsyncTask<String, Void, Boolean> yesTask,
                       final AsyncTask<String, Void, Boolean> noTask) {

    AlertDialog dialog = new AlertDialog.Builder(act).create();
    dialog.setTitle(title);
    dialog.setMessage(confirmText);
    dialog.setCancelable(false);
    dialog.setButton(DialogInterface.BUTTON_POSITIVE, yesButtonText,
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int buttonId) {
                yesTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
        });
    dialog.setButton(DialogInterface.BUTTON_NEGATIVE, noButtonText,
        new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int buttonId) {
                if(noTask!=null) {
                    noTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                }

            }
        });
    dialog.setIcon(android.R.drawable.ic_dialog_alert);
    dialog.show();
}
 YourTask yourTask =  new YourTask( ... );
 confirm( YourActivity.this, 
         "Confirm", 
         "Are you sure?", 
         "Cancel", 
         "Continue", 
         yourTask,
         null);
public class MyDialogs {

// private constructor
public Runnable answerTrue = null;
public Runnable answerFalse = null;

// Dialog. --------------------------------------------------------------

public boolean confirm(Activity act, String Title, String ConfirmText,
                       String noBtn, String yesBtn, Runnable yesProc, Runnable noProc) {
    answerTrue = yesProc;
    answerFalse= noProc;
    AlertDialog.Builder alert = new AlertDialog.Builder(act);
    alert.setTitle(Title);
    alert.setMessage(ConfirmText);
    alert.setCancelable(false);
    alert.setPositiveButton(R.string.button_positive, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            answerTrue.run();
        }
    });
    alert.setNegativeButton(R.string.button_negative, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            answerFalse.run();
        }
    });
    alert.show().getButton(DialogInterface.BUTTON_NEGATIVE).requestFocus();
    return true;
}