简体   繁体   中英

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?

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:

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.

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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