Currently when the user opens my app, an AlertDialog opens, asking them if they would like to upgrade to the pro version.
I need to add a CheckBox
The way to make a checkbox list is to use setMultiChoiceItems in the AlertDialog.
// Set up the alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("Choose some animals");
// Add a checkbox list
String[] animals = {"horse", "cow", "camel", "sheep", "goat"};
boolean[] checkedItems = {true, false, false, true, false};
builder.setMultiChoiceItems(animals, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// The user checked or unchecked a box
}
});
// Add OK and Cancel buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// The user clicked OK
}
});
builder.setNegativeButton("Cancel", null);
// Create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
Here I hard coded which items in the list were already checked. It is more likely that you would want to keep track of them in an ArrayList. See the documentation example for more details. You can also set the checked items to null if you always want everything to start unchecked.
For context, you can use this if you are in an Activity.
My fuller answer is here.
// Set up the alert builder
val builder = AlertDialog.Builder(context)
builder.setTitle("Choose some animals")
// Add a checkbox list
val animals = arrayOf("horse", "cow", "camel", "sheep", "goat")
val checkedItems = booleanArrayOf(true, false, false, true, false)
builder.setMultiChoiceItems(animals, checkedItems) { dialog, which, isChecked ->
// The user checked or unchecked a box
}
// Add OK and Cancel buttons
builder.setPositiveButton("OK") { dialog, which ->
// The user clicked OK
}
builder.setNegativeButton("Cancel", null)
// Create and show the alert dialog
val dialog = builder.create()
dialog.show()