我正在制作一个小游戏,我试图显示一个AlertDialog,问题是,当用户单击一个选项时,AlertDialog不会消失。
我正在使用循环程序,因此当我的 AlertDialog 出现时,我的游戏线程会停止(循环程序),并且当用户单击“取消”时,游戏线程会再次运行,但对话框位于顶部,用户无法继续玩。
public void alert() {
Looper.prepare();
myHandler = new Handler();
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(_context);
LayoutInflater factory = LayoutInflater.from(_context);
final View view = factory.inflate(R.layout.custom_dialog, null);
alertBuilder.setView(view);
alertBuilder.setNeutralButton("Take Photo", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
stops++;
Toast.makeText(_context.getApplicationContext(), "Photo Taken", Toast.LENGTH_SHORT).show();
}
});
alertBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
System.out.println("Stops = " + stops);
stops++;
Toast.makeText(_context.getApplicationContext(), "Canceled", Toast.LENGTH_SHORT).show();
myHandler.getLooper().quit();
dlg.dismiss();
}
});
alertBuilder.show();
Looper.loop();
}
应该是
alertadd.dismiss();
。而不是dlg.dismiss();
尝试一下。如果不告诉我...
不确定是否有帮助,但尝试一下
dlg.cancel();
或者看看这个。在我的情况下它工作得很好:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(getString(R.string.a))
.setCancelable(false)
.setPositiveButton(getString(R.string.b), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton(getString(R.string.c), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
您必须先创建警报对话框,然后在 onClick 方法中使用它的 dismiss() 方法:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
AlertDialog alert = builder.create();
builder.setMessage(getString(R.string.a))
.setCancelable(false)
.setPositiveButton(getString(R.string.b), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton(getString(R.string.c), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alert.dismiss();
}
});
alert.show()