简体   繁体   English

动态添加它们时如何查看选中了哪个复选框

[英]how to see which checkbox is checked when add them dynamically

I have a XML with a TextView and a CheckBox in it, now I add them to an Activity, how many I add depends on how many questions there are, but if a checkbox is checked I want to see which one, how can I do this? 我有一个带有TextViewCheckBox的XML,现在将它们添加到Activity中,我添加的数量取决于有多少个问题,但是如果选中了一个复选框,我想查看哪个问题,我该怎么办这个?

for (int i = 0; i< questions.size(); i++) {

    View view1 = View.inflate(Checklist.this, R.layout.question, null);
    TextView myText = (TextView) view1.findViewById(R.id.questiontext);
    checkbox = (CheckBox) view1.findViewById(R.id.checkBox);
    layout.addView(view1);
    myText.setText(questions.get(i).question);

    checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
           //check which checbox is checked
        }
    });

}

This is how is add them to my view. 这是将它们添加到我的视图的方式。

You can use setTag to set tag on a checkbox: 您可以使用setTag在复选框上设置标签:

While creating: 创建时:

for (int i = 0; i< questions.size(); i++) {

    View view1 = View.inflate(Checklist.this, R.layout.question, null);
    TextView myText = (TextView) view1.findViewById(R.id.questiontext);
    checkbox = (CheckBox) view1.findViewById(R.id.checkBox);
    checkbox.setTag(String.valueOf(i));
    layout.addView(view1);
    myText.setText(questions.get(i).question);

    checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
           //check which checbox is checked
           String tag= (String)buttonView.getTag();
        }
    });
}

This would give you tag (i), that will indicate the question number. 这将为您提供标签(i),该标签将指示问题编号。

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM