Reputation: 4956
I have created multiple checkboxes via applying looping.
for(int l=0;l<len;l++)
{
chkBox = dynamicUiComponents.myCheckBox(context, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT), 100+i, "Unchecked", opts[l]);
myLayout.addView(chkBox);
}
All the check boxes are showing. But when I am applying setOnCheckedChangeListener(l) on that check box, then only last added check box text is printer. Its because every time in loop, I provide a new object reference to the chkBox variable. So here how to identify that which chechbox is clicked.
Upvotes: 0
Views: 163
Reputation: 618
You can set a different tag for each Checkbox and set the listener on THIS, you activity should implement the listener and then do whatever you want when the event is trigger.
Upvotes: 0
Reputation: 6487
Try the following
for(int l=0;l<5;l++)
{
chkBox = new CheckBox(context);
myLayout.addView(chkBox);
chkBox.setTag(""+l);
chkBox.setOnCheckChangeListener(new ...(){
int x = Integer.ValueOf(chkBox.getTag());
//do whatever you want to do here
});
}
Upvotes: 0
Reputation: 5322
In your code, you did not create an array of CheckBoxes
, you only created one. So, using setOnCheckChangedListener(I)
will not refer to the checkBox
. Either you set the listener inside the loop, or give each a unique ID to refer to it later and set the listener:
for(int l=0;l<5;l++) { chkBox = new CheckBox(context);
chkBox.setOnCheckChangedListener(
//your implementation
);
myLayout.addView(chkBox); }
Upvotes: 1
Reputation: 340
you can add id to tag:
for(int id=0;id<5;id++) {
chkBox = new CheckBox(context);
chkBox.setTag(id);
myLayout.addView(chkBox);
}
and you may use:
Integer i = (Integer) chkBox.getTag();
Upvotes: 0