Android Dynamic Checkbox issue
I am in the process of trying to add dynamic checkbox to my activity. However being a beginner i cant get round the basics of being able to add checkboxes and remove them. Here is my code....
private void createCheckbox() {
for(int i=0; i<5; i++){
cb = new CheckBox(this);
ll.addView(cb);
cb.setText("Test");
}
ll.addView(submit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for(int i = 0; i < 5; i++) {
ll.removeView(cb);
}
ll.removeView(submit);
Questions();
}});
} ll is a linerlayout object. The idea is when the code runs, 5 checkboxes appear and then once the user clicks on the submit button they get removed. Currently the boxes are being seen, but when the submit button is pressed only one of the five is being removed. I don't understand what i am doing wrong?
The idea is that the checkboxes will be creating depending on a value with the database and this value could change thats why the checkboxes are not predefined as there could be 4, 5, or 15. I dont know how to make each checkbox have its own identifier, because after this issue i will need to identify them individually because i will need to add text to them from the databa开发者_如何学JAVAse and then once the user has check a few buttons i will need to save this into a seperate table. Very confused !!! help!
You need to store the references to those checkboxes somewhere, but not reusing the same variable.
CheckBox[] cbs = new CheckBox[5];
for(int i=0; i<5; i++){
cbs[i] = new CheckBox(this);
ll.addView(cb);
cbs.setText("Test");
}
ll.addView(submit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for(int i = 0; i < 5; i++) {
ll.removeView(cbs[i]);
}
ll.removeView(submit);
Questions();
}});
精彩评论