Reputation: 1959
I am creating an android app where there are 20 checkboxes to be shown to user for multiple selection. I have programmed to display the checkbox dynamically but the problem is how to get the checked box value ? I have tried this code so far.
my global variables are
ArrayList<MyCheckBox> listOfCheckedItem;
private int CHECKBOX_POSITION;
and for adding checkboxes I did something like this
listOfCheckedItem = new ArrayList<>();
listOfCheckedItem.add(new MyCheckBox(true, "One")); //(isChecked,text)
listOfCheckedItem.add(new MyCheckBox(false, "Two"));
listOfCheckedItem.add(new MyCheckBox(true, "Three"));
listOfCheckedItem.add(new MyCheckBox(false, "four"));
listOfCheckedItem.add(new MyCheckBox(false, "five"));
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
for (int i = 0; i < listOfCheckedItem.size(); i++) {
CHECKBOX_POSITION = i;
MyCheckBox myCheckBox = listOfCheckedItem.get(i);
CheckBox checkBox = new CheckBox(this);
checkBox.setChecked(myCheckBox.getIsChecked());
checkBox.setText(myCheckBox.getText());
selectCategoryLayout.addView(checkBox, params);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listOfCheckedItem.get(CHECKBOX_POSITION).setIsChecked(isChecked);
}
});
}
And to get the check boxes value I did like this
StringBuilder builder = new StringBuilder();
for (int i = 0; i < listOfCheckedItem.size(); i++) {
MyCheckBox mcb = listOfCheckedItem.get(i);
builder.append("\nstatus: " + mcb.getText() + " is " + mcb.getIsChecked());
}
resultView.setText(builder.toString());
For the first time when I run app every checkboxes are shown correctly and when I click on button to get the check boxes (checked/unchecked) value it shows the correct result, But when I check/uncheck any one of the checkboxes and again click on the button to get the result only last checkbox value is changed. What I am missing I cannot figure it out.
Upvotes: 0
Views: 699
Reputation: 1959
problem solved, Instead of doing this
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
listOfCheckedItem.get(CHECKBOX_POSITION).setIsChecked(isChecked);// changed this line as below code
}
});
I did like this
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
myCheckBox.setIsChecked(isChecked);//I changed this line and every thing worked fine
}
});
Upvotes: 0