Reputation: 27
I am creating an alert dialog with a custom layout and I want to cancel the dialog box when I press one of the layout's buttons.
LayoutInflater layoutInflater = LayoutInflater.from(GroupAdminOptions.this);
View alertView = layoutInflater.inflate(R.layout.change_group_name, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(GroupAdminOptions.
this);
final EditText userInput = (EditText) alertView.findViewById(R.id.editTextUserInput);
Button okButton = (Button) alertView.findViewById(R.id.okButton);
Button cancelButton = (Button) alertView.findViewById(R.id.cancelButton);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("QQQ","" + userInput.getText());
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("QQQ","cancel");
}
});
alertDialogBuilder.setView(alertView);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
It is possible to cancel alertDialog when I press cancel button?
Upvotes: 1
Views: 2765
Reputation:
It is possible to cancel alertDialog when I press cancel button?
yes, you need to call dialog.dismiss()
in your cancelButton.setOnClickListener(...)
Upvotes: 0
Reputation: 6834
Try defining the OnClickListeners after calling alertDialogBuilder.show(), then you can call alertDialog.dismiss() from inside them. E.g.
final AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
Button okButton = (Button) alertView.findViewById(R.id.okButton);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("QQQ","" + userInput.getText());
alertDialog.dismiss();
}
});
Button cancelButton = (Button) alertView.findViewById(R.id.cancelButton);
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("QQQ","cancel");
alertDialog.dismiss();
}
});
Upvotes: 2
Reputation: 12861
You have to make AlertDialog
as global variable then you can use AlertDialog
inside onClick()
method then dismiss it.
Try this code after declaring alertDialog as global variable.
cancelButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("QQQ","cancel");
alertDialog.dismiss();
}
});
I hope it helps!
Upvotes: 3