2012-08-12 70 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