我正在尝试实现此代码
if(someCondition){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("message")
.setPositiveButton("Yes", this)
.setNegativeButton("No", this);
builder.show();
}
finish();
问题是活动在显示对话框之前调用finish(),因此会抛出以下异常
MyActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40704090 that was originally added here
如何处理?
答案 0 :(得分:3)
if(someCondition){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("message")
.setPositiveButton("Yes", this)
.setNegativeButton("No", this);
builder.show();
} else {
finish();
}
在按钮的处理程序中,再次点击完成。
答案 1 :(得分:3)
关闭对话框时,使用OnDismissListener致电finish()
。这样用户就可以响应对话框,活动仍然可以关闭。
if(someCondition) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("message");
.setPositiveButton("Yes", this)
.setNegativeButton("No", this);
AlertDialog dialog = builder.create();
dialog.setOnDismissListener(new OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) {
finish();
}
});
dialog.show();
}
else {
finish();
}
答案 2 :(得分:0)
您收到以下错误:
MyActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@40704090 that was originally added here
因为必须在活动结束前解雇建筑商。所以我想你必须重新设计你希望你的活动完成的方式。也许您希望在单击“否”按钮时完成?
我希望这会有所帮助。
答案 3 :(得分:0)
我不确定问题究竟是什么,但您得到的错误是因为您在显示对话框时完成了活动。我经常做的是在我的活动的dialog.dismiss()
或onPause
方法中拨打onStop
。
这段代码怎么样?:
活动中的某些地方;
private AlertDialog dialog;
onPause或onStop方法,
@Override
public void onPause() {
super.onPause();
if(dialog != null){
dialog.dismiss();
}
}
构建对话框,
if(someCondition){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("message")
.setPositiveButton("Yes", new OnClickListener(){
public void onClick(DialogInterface arg0, int arg1) {
//do stuff
//finish?
}
});
.setNegativeButton("No", new OnClickListener(){
public void onClick(DialogInterface arg0, int arg1) {
//do stuff
//finish?
}
});
dialog = builder.show();
}