[英]Dismissing Alert Dialog with custom interface using custom button
I have a custom alert dialog. 我有一个自定义警报对话框。 I am currently trying to alter the onclicklisteners for my two buttons.
我目前正在尝试更改两个按钮的onclicklisteners。 Previously I have used the following code.
以前,我使用以下代码。
builder.setNegativeButton("Nope", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
\\code here which is not relevant to question
}
});
However, now since the dialog has a custom view and custom buttons, I use the following approach. 但是,由于对话框具有自定义视图和自定义按钮,因此我使用以下方法。
Button confirm = (Button) windowView.findViewById(R.id.confirmbutton);
Button cancel = (Button) windowView.findViewById(R.id.negatebutton);
cancel.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v){
}
});
My question is how do I dismiss the dialog within the cancel button listener if I can't access the dialog
variable. 我的问题是,如果我无法访问
dialog
变量,如何在取消按钮侦听器中关闭dialog
。 I want to use the AlertDialog
I am already using and do not want a solution with a different type of dialog. 我想使用我已经在使用的
AlertDialog
并且不希望使用其他类型的对话框的解决方案。
What you need to do, is just keep a reference of the Dialog, then you can call the dismiss method. 您需要做的只是保留Dialog的引用,然后可以调用dismiss方法。 In my example, i keep the reference as a property.
在我的示例中,我将引用保留为属性。
private Dialog dialog;
@Override
public void onResume() {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
LinearLayout llView = new LinearLayout(this);
Button btnDismiss = new Button(this);
btnDismiss.setOnClickListener(new Button.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
llView.addView(btnDismiss);
adb.setView(llView);
dialog = adb.create();
dialog.show();
super.onResume();
}
It's important keep the reference as a property, cause the reference must be final to be accessible inside the onClick method, and since the dialog it's not created yet, you cant keep the final reference in a method variable, then keep it in a property. 务必将引用保留为属性,因为该引用必须是最终引用,才能在onClick方法中访问,并且由于尚未创建对话框,因此您不能将最终引用保留在方法变量中,然后将其保留在属性中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.