如何获取动态复选框ID?

How to get dynamic check box id?

我在我的项目中使用以下代码创建了动态复选框,我如何获取复选框 ID 并为其创建命令,例如:

if(checkbox1.ischecked()==true){
//do 
}

提前致谢。

public void fetchContacts() {
    final LinearLayout Vll=(LinearLayout)findViewById(R.id.Vll);

    CheckBox cb = new CheckBox(getApplicationContext());
                        cb.setText(outputName+":"+outputNumber);
                        Vll.addView(cb);
}

你可以这样做

cb.setId(anyPositiveInteger)

试试这个了解更多详情How can I assign an ID to a view programmatically?

您应该将对所有 CheckBox 的所有引用存储在 ArrayList

List<CheckBox > allCheckBox = new ArrayList<CheckBox>();

当您创建任何 CheckBox 时,您需要将其添加到您的 List

CheckBox cb = new CheckBox(getApplicationContext());
...
allCheckBox.add(cb);

之后您可以通过

访问CheckBox
allCheckBox.get(position).isChecked() == true
// allCheckBox.get(position) -> with return a CheckBox
// position is the index when you add checkbox to ArrayList, for example you have create 2 CheckBox dynamic
// then CheckBox1 is allCheckBox.get(0) and CheckBox2 is allCheckBox.get(1)