在Android中检查多个复选框

Mud*_*sir 3 checkbox android

CheckBox checkOne = (CheckBox) findViewById(R.id.checkOne);
checkOne.setSelected(true);

CheckBox checkTwo = (CheckBox) findViewById(R.id.checkTwo);
checkTwo.setSelected(true);

CheckBox checkThree = (CheckBox) findViewById(R.id.checkThree);
checkThree.setSelected(true);
Run Code Online (Sandbox Code Playgroud)

我使用上面的代码来检查或取消选中多个复选框.

我的问题是,有什么方法可以立刻获得所有复选框吗?(我不想使用数组)例如,我的复选框位于LinearLayout中,所以我可以将所有复选框作为LinearLayout的子项吗?

mai*_*450 6

如果父LinearLayout 仅包含复选框,则可以执行以下操作:

//ll is the LinearLayout holding the children
for(int i = 0; i < ll.getChildCount(); i++) {
    ((CheckBox)ll.getChildAt(i)).setChecked(true);
}
Run Code Online (Sandbox Code Playgroud)

如果你在LinearLayout中有更多的视图,你可以像这样添加一个检查:

for(int i = 0; i < ll.getChildCount(); i++) {
    View v = ll.getChildAt(i);
    if(v instanceof CheckBox) {
        ((CheckBox)v).setChecked(true);
    }
}
Run Code Online (Sandbox Code Playgroud)