Reputation: 8705
I am showing a simple Alert Dialog with OK/Cancel buttons. When user clicks OK, some code runs - that needs a parameter.
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
alertDialogBuilder
.setTitle("Are you sure?")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//TODO: Do something with parameter.
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
How do i pass the parameter to AlertDialog?
Upvotes: 5
Views: 11548
Reputation: 1
You can also use static variables in app. Define public static String SumValue="";
Suppose My calling class is MainActivity Class then, I can initiate the variable before calling dialog like
MainActivity.SumValue="Test Value"; addcartdialog addcartdialog = new addcartdialog(); addcartdialog.show( ((AppCompatActivity) context).getSupportFragmentManager(),"Add Cart");
In addcartdialog class
you can assign to textView = view.findViewById(R.id.servingsTxt); textView = MainActivity.SumValue;
In this way you can work with multiple variables in alertdialog.
Upvotes: -2
Reputation: 24417
If you declare the variable as final
then you can set it in your code before calling AlertDialog.Builder() and then access it in the onClick(), like this:
final int someParameter = someValue;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
alertDialogBuilder
.setTitle("Are you sure?")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Do something with parameter.
doSomeStuff(someParameter);
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
This way, someParameter is implicitly passed to onClick() via a function closure, so there is no need to subclass AlertDialog or add extra member variables to your Activity.
Upvotes: 10