【问题标题】:How to get id from dynamically added checkbox and them value如何从动态添加的复选框中获取 id 及其值
【发布时间】:2016-05-12 04:13:54
【问题描述】:

我想获得动态添加的 CheckBox 的价值,但是当我想查看我的 checkBox.isChecked();只有当我检查创建的最后一个复选框时它才会响应!这是我的容器。

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);


        }

我想检查它是这样检查的:

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");
         }

        }
    });

在谷歌上没有找到正确的答案! 感谢您的帮助

【问题讨论】:

标签: java android checkbox


【解决方案1】:

当您调用 et_button.isChecked() 时,它会在最后一个膨胀视图上调用,因为您在循环的每次迭代中都会覆盖它。 您应该将它们添加到 List 中,然后在 onClickListener 中检查选中的是哪一个:

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");
         }
      }
    }
});

尚未测试,但应该可以。

【讨论】:

  • 它正在工作,所以你只需将每个复选框添加到列表中,但我不明白 for(CheckBox cb : list) 的循环,你能解释一下吗?
  • 需要 for 循环,因为每个复选框都是具有其 ID 的不同对象,如果没有循环,您将检查添加的最后一个对象的 ID,如果选中,则检查添加的每个复选框.如果对您有用,请考虑接受答案!
猜你喜欢
  • 1970-01-01
  • 2016-01-29
  • 2014-05-16
  • 2016-11-15
  • 1970-01-01
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多