1

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

Friedrich Dylan
  • 114
  • 1
  • 11

1 Answers1

1

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.

shmosel
  • 49,289
  • 6
  • 73
  • 138
Lorenzo Barbagli
  • 1,241
  • 2
  • 16
  • 34
  • It's working, so you just add each checkbox in a list but i don't understand the loop for(CheckBox cb : list) can u explain please ? – Friedrich Dylan May 11 '16 at 20:18
  • The for loop is needed because every checbox is a different object with its ID, without the loop you are checking the ID of the last object added, with the loop you check for every checbox added if it's checked . Please consider accepting the answer if it works for you! – Lorenzo Barbagli May 12 '16 at 06:33