1

我创建了一个AlertDialog并将其放在一个Button OnClickListener. 但是,该对话框正在使我的应用程序崩溃。

我的代码有什么问题?

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) {
            MyActivity.this.finish();
       }
   })
   .setNegativeButton("No", new DialogInterface.OnClickListener() {
       public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
       }
   });
AlertDialog alert = builder.create();
4

3 回答 3

2

尝试添加

dialog.dismiss();

MyActivity.this.finish();
于 2012-08-12T10:26:09.627 回答
1

检查以下代码。有用

   public class MainActivity extends Activity {
   CharSequence[] items = { “Google”, “Apple”, “Microsoft” };
        boolean[] itemsChecked = new boolean [items.length];
     /** Called when the activity is first created. */
      @Override
             public void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
             Button btn = (Button) findViewById(R.id.btn_dialog);
               btn.setOnClickListener(new View.OnClickListener() {
       public void onClick(View v) {
            showDialog(0);
       }
         });
     }
      @Override
         protected Dialog onCreateDialog(int id) {
         switch (id) {
         case 0:
          return new AlertDialog.Builder(this)
       .setIcon(R.drawable.icon)
       .setTitle("This is a dialog with some simple text...")
         .setPositiveButton("OK", new
        DialogInterface.OnClickListener() {
          public void onClick(DialogInterface dialog,
            int whichButton)
      {
        Toast.makeText(getBaseContext(),
                               "OK clicked!", Toast.LENGTH_SHORT).show();
          }
         })
    .setNegativeButton("Cancel", new
    DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog,
     int whichButton)
     {
       Toast.makeText(getBaseContext(),
       "Cancel clicked!", Toast.LENGTH_SHORT).show();
       }
      })
      )
     .create();
     }
    return null;
       }
      }
于 2012-08-12T10:15:23.010 回答
0

试试这个:

AlertDialog.Builder builder = new AlertDialog.Builder(Json_ReadActivity.this);
builder.setMessage("are you sure want to exit");
builder.setNeutralButton("Ok",new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        Toast.makeText(getApplicationContext(),"text",Toast.LENGTH_LONG).show();
    }
});

builder.show();
于 2012-08-12T10:10:44.793 回答