我创建了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();
答案 0 :(得分:2)
尝试添加
dialog.dismiss();
前
MyActivity.this.finish();
答案 1 :(得分: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;
}
}
答案 2 :(得分: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();