I have dynamically created checkbox.I want Id of selected checkbox.but I am getting Id of only last checkbox. for eg. if 5 checkboxes created then it is showing Id of 5th checkbox only when clicked.I want Id of all 5 checkbox.
Here is my dynamic created checkbox class.
private void getcheckbox()
{
int cnter;
linearMain = (LinearLayout) findViewById(R.id.linearLayout2);
alphabet = new LinkedHashMap<String, String>();
for (cnter = 0; cnter < str_arr;)
if (!optionsarray.get(cnter).isEmpty())
{
cnter++;
} else
break;
alphabet.put("1", Option_A_new);
alphabet.put("2", Option_B_new);
alphabet.put("3", Option_C_new);
alphabet.put("4", Option_D_new);
alphabet.put("5", Option_E_new);
alphabet.put("6", Option_F_new);
alphabet.put("7", Option_G_new);
alphabet.put("8", Option_H_new);
alphabet.put("9", Option_I_new);
alphabet.put("10", Option_J_new);
Set<?> set = alphabet.entrySet();
Iterator<?> i = set.iterator();
int cnt = 0;
while (cnt < cnter)
{
@SuppressWarnings("rawtypes")
final Map.Entry me = (Map.Entry) i.next();
checkBox = new CheckBox(this);
checkBox.setId(Integer.parseInt(me.getKey().toString()));
checkBox.setTextColor(getResources().getColor(R.color.black));
checkBox.setText(me.getValue().toString());
linearMain.addView(checkBox);
cnt++;
}
Here is my another class for checking selescted checkbox Id
checkBox.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
int checkBoxId = ((CheckBox) v).getId();
switch(checkBoxId) {
case 1:
selectedcheckboxid ="A";
testAnswernew(selectedcheckboxid);
break;
case 2:
selectedcheckboxid = "B";
testAnswernew(selectedcheckboxid);
break;
case 3:
selectedcheckboxid = "C";
testAnswernew(selectedcheckboxid);
break;
case 4:
selectedcheckboxid = "D";
testAnswernew(selectedcheckboxid);
break;
case 5:
selectedcheckboxid = "E";
testAnswernew(selectedcheckboxid);
break;
case 6:
selectedcheckboxid = "F";
testAnswernew(selectedcheckboxid);
break;
case 7:
selectedcheckboxid = "G";
testAnswernew(selectedcheckboxid);
break;
case 8:
selectedcheckboxid = "H";
testAnswernew(selectedcheckboxid);
break;
case 9:
selectedcheckboxid = "I";
testAnswernew(selectedcheckboxid);
break;
case 10:
selectedcheckboxid = "J";
testAnswernew(selectedcheckboxid);
break;
default:
}
the problem is, that you adding a clicklistener just to the last added checkbox! So add a listener to the checkbox in your while loop.