Friedrich Dylan
Friedrich Dylan

Reputation: 142

How to get id from dynamically added checkbox and them value

I want to get value for dynamically added CheckBox but when i want to see if one of my checkBox.isChecked(); it only respond when i check the last checkbox created ! Here is my container.

for (String answer : multiMap.get(questionFromMultiMap))
        {

            i++;
            et_button = (CheckBox) getLayoutInflater().inflate(R.layout.numberofchoices, null);
            et_button.setText(answer);
            et_button.setId(i);
            container.addView(et_button);
            listOfChoice.add(answer);


        }

I want to check it's checked like that :

btnCorrect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

         if (et_button.isChecked()){
             System.out.println(et_button.getId());
         }else{
             System.out.println("pouet");
         }

        }
    });

Didn't find right answer on google ! Thanks for help

Upvotes: 1

Views: 1670

Answers (1)

Lorenzo Barbagli
Lorenzo Barbagli

Reputation: 1281

When you call et_button.isChecked() this is called on the last inflated view, cause you are overwriting it every iteration of the loop. You should add them in a List instead, and then in the onClickListener check which one is checked:

List<CheckBox> list = new LinkedList<>(); //this should be visible from onClickListener, so it should be an instance field

for (String answer : multiMap.get(questionFromMultiMap)) {
        i++;
        CheckBox et_button = (CheckBox) getLayoutInflater().inflate(R.layout.numberofchoices, null);
        et_button.setText(answer);
        et_button.setId(i);
        list.add(et_button);
        container.addView(et_button);
        listOfChoice.add(answer);
    }

btnCorrect.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      for(CheckBox cb : list) {
         if (cb.isChecked()){
             System.out.println(cb.getId());
         }else{
             System.out.println("pouet");
         }
      }
    }
});

Haven't tested it but It should work.

Upvotes: 1

Related Questions