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();
}
}