如何在android中获得DialogResult?

时间:2011-05-10 06:08:56

标签: android

我想用两个按钮'YES'和'NO'创建一个DialogAlert。我想在布尔变量中捕获Dialog的结果。假设用户单击“YES”按钮,则DialogResult应返回true值,如果用户单击“NO”按钮,则DialogResult应返回False值。请帮我解决这个问题。提前谢谢。

2 个答案:

答案 0 :(得分:4)

我会使用AlertDialog(see documentation here)。如果您有自己的类DialogResult,代码可能如下所示:

DialogResult result = new DialogResult(); 
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
   .setCancelable(false)
   .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            // User clicked Yes: set the value to your result class here. E.g:
            MyActivity.result.setValue(true);
       }
   })
   .setNegativeButton("No", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            // User clicked No: set the value to your result class here. E.g: 
            MyActivity.result.setValue(false);
       }
   });
AlertDialog alert = builder.create();

答案 1 :(得分:3)

试试此代码

boolean result;
AlertDialog.Builder invalid_input_dialog = new AlertDialog.Builder(Select_party_foods1.this);
          invalid_input_dialog.setTitle("Event Organise")
          .setMessage(dialog_message)
          .setCancelable(true)
          .setPositiveButton("Ok", new DialogInterface.OnClickListener(){
              @Override
                public void onClick(DialogInterface dialog, int which) {
                 result=true;
                System.out.println("The result is "+result);
              }
          })
          .setNegativeButton("No", new DialogInterface.OnClickListener(){

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                result=false;
                System.out.println("The result is "+result);                        
            }

          })
          .show();