Reputation: 368
I have a MultiChoice AlertDialog where I have 25 choices.
I want to let the user select only any 5 out of 25.
When she selects the 6th choice I want to unckeck it and show a Toast message which says that only 5 choices she can make.
Is it possible with MultiChoice AlertDialog? Please help!
Upvotes: 4
Views: 3064
Reputation: 13
Instead of LunaVulpo's solution I used
if (((AlertDialog) dialog).getListView().getCheckedItemCount() > 2) {
...
}
Because the count resets, while the checked items still remain, when the user opens the Alertdialog again to edit his choices.
Upvotes: 1
Reputation: 3221
The exact solution for OP is:
final boolean[] selected = new boolean[25];
builder.setMultiChoiceItems(R.array.values, selected, new DialogInterface.OnMultiChoiceClickListener() {
int count = 0;
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
count += isChecked ? 1 : -1;
selected[which] = isChecked;
if (count > 5) {
Toast.makeText(getActivity(), "You selected too many.", Toast.LENGTH_SHORT).show();
selected[which] = false;
count--;
((AlertDialog) dialog).getListView().setItemChecked(which, false);
}
}
});
Upvotes: 15
Reputation: 3679
Create a static variable "count" and increment it on the option selected, and decrement when its deselected on the onclick event of the checkbox. As follows :
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class AlertWithCheckBoxActivity extends Activity {
/** Called when the activity is first created. */
static int count = 0;
final CharSequence[] items={".NET","J2EE","PHP"};
boolean[] itemsChecked = new boolean[items.length];
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void showDialog(View v)
{
count = 0;
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setTitle("Pick a Choice");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String selectedTech="Selected Tech - ";
for (int i = 0; i < items.length; i++) {
if (itemsChecked[i]) {
selectedTech=selectedTech+items[i]+" ";
itemsChecked[i]=false;
}
}
}
});
builder.setMultiChoiceItems(items, new boolean[]{false,false,false}, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if(isChecked) {
if(count < 5) {
itemsChecked[which] = isChecked;
count++;
}else{
//Display your toast here
}
}else{
count--;
}
}
});
builder.show();
}
}
Upvotes: 2