Reputation: 2140
I have util class for dialogs with a function:
public static void buildCustomDialog(Context contextRef, View dialogContentView)
{
AlertDialog.Builder builder = new AlertDialog.Builder(contextRef);
builder.setView(dialogContentView);
builder.setNegativeButton(contextRef.getString(R.string.std_cancel), null);
AlertDialog dialog = builder.create();
dialog.show();
}
and the view that I pass it has two buttons with clickListeners. Everything works great EXCEPT that I can't dismiss the dialog when the user clicks one of the custom buttons. So they navigate to another page, hit back and the dialog is still there.
How can I get a reference to the dialog in the custom clickListeners I'm creating before the dialog is made?
I've tried every conceivable option. My latest attempt is to make a custom DialogFragment with a custom interface but even then, the view (and hence the buttons and their listeners) get created before the AlertDialog builder creates the dialog.
I feel like this should be super simple and I'm missing something ...
Upvotes: 5
Views: 3692
Reputation: 1452
In Kotlin something like this (using Anko dialogs) This shows list of buttons in custom layout, each closes dialog:
private var closeDialogAction: () -> Unit = {}
private fun showDialog(greetings: List<Greeting>) {
val alert = context.alert {
customView {
verticalLayout {
greetings.forEach {
textView {
text = it.name
setOnClickListener {
// Make some other necessary actions
closeDialogAction()
}
}
}
}
}
}.build()
closeDialogAction = {alert.dismiss()}
alert.show()
}
Upvotes: 0
Reputation: 379
Easy. return dialog reference, collect it where you invoke this method. Check in your dismiss button listener that if dialog reference holds valid object. If yes then dismiss this dialog.
Upvotes: 0
Reputation: 779
You need to set onClick
listener on your custom button.
Try this :
AlertDialog.Builder builder = new AlertDialog.Builder(contextRef);
builder.setView(dialogContentView);
Button btnOk= (Button) dialogContentView.findViewById(R.id.btn_ok);
builder.setNegativeButton(contextRef.getString(R.string.std_cancel), null);
AlertDialog dialog = builder.create();
dialog.show();
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
That's it !!
Upvotes: 15