2012-08-12 68 views
1

我创建了一个AlertDialog,并将其放在ButtonOnClickListener上。 但是,该对话框正在崩溃我的应用程序。显示AlertDialog会导致我的应用程序崩溃。

我的代码有什么问题?

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(); 
+1

你怎么在logcat中看到了什么?有什么例外? – Madushan 2012-08-12 10:11:09

+0

当您尝试显示对话框或与其交互时,应用程序是否会崩溃?你的代码看起来没问题,它是什么,但它需要更多的上下文。我建议发布更多的Activity代码会有所帮助,至少是onCreate()和onCreateDialog()方法。另外,正如Madushan所说,logcat的内容也将为原因提供强有力的线索。 – Chilledrat 2012-08-13 10:09:08

回答

2

尝试添加

dialog.dismiss(); 

MyActivity.this.finish(); 
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(); 
+0

您是否认为这有助于解决这个问题? – 2012-08-12 11:05:17

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; 
     } 
     } 
+1

您是否认为这有助于解决问题? – 2012-08-12 11:03:13