Vanhaeren Thomas
Vanhaeren Thomas

Reputation: 387

Get generated checkbox Checked State

I generate checkboxes with the following code:

public void drawCAnswers(int pst){
    rcflag = 1;
    int drawables = qmclist.get(pst).getAnswers().size();
    LinearLayout ll = new LinearLayout(this);
    CheckBox[] cbs = new CheckBox[drawables];
    ll.setOrientation(LinearLayout.VERTICAL);
    for (int i=0; i<drawables;i++){
        cbs[i] = new CheckBox(this);
        cbs[i].setId(i);
        cbs[i].setText(current.getAnswers().get(i).getAns());
        ll.addView(cbs[i]);
    }
    parentLinearLayout.addView(ll, parentLinearLayout.getChildCount());
}

I would like to be able, upon clicking a button, to check which of the checkboxes are selected, and get their text. How exactly could I accomplish this with my code?

Setting an onClick Listener doesn't seem right, because it's only when I click the "Next" button that I should see which ones are checked, it doesn't matter if before clicking someones (de)selects a checkbox.

For example, in the image below, it's when I click on "Question suivante" that I should get the text of the two selected checkboxes, and eventually save them in some list.

enter image description here

Thanks a lot.

Upvotes: 0

Views: 29

Answers (1)

Tung Tran
Tung Tran

Reputation: 2955

You try get string and store into list when facing checked change event. Try this:

List<String> yourList = new ArrayList<>();

for (int i=0; i<drawables;i++){
    cbs[i] = new CheckBox(this);
    cbs[i].setId(i);
    cbs[i].setText(current.getAnswers().get(i).getAns());
    cbs[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    yourList.add(buttonView.getText().toString());
                } else {
                    yourList.remove(buttonView.getText().toString());
                }
            }
    });
    ll.addView(cbs[i]);
}

Upvotes: 1

Related Questions