3

我在 LinearLayout 中以编程方式添加了几个复选框。是否可以找到并检查 LinearLayout 中的所有复选框?我的xml结构如下:

<LinearLayout>
<ScrollView>
<TableLayout>
<TableRow>
<CheckBox>
</TableRow>
<TableRow>
<CheckBox>
</TableRow>
</TableLayout>
</ScrollView>
</LinearLayout>

Java 代码:

CheckBox selectAll = (CheckBox)findViewById(R.id.checkboxSelectAll);
selectAll.setOnCheckedChangeListener(new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    if(buttonView.isChecked()){
        //loop in linear layout
            //find each checkbox
            //setChecked(true);

    }

}
});
4

2 回答 2

3

您可以保留复选框的引用,也可以使用 getChildCount() 然后 getChildAt 循环遍历所有元素,然后检查元素是否为 (instanceof) CheckBox 类型,以及是否只是将其转换为 CheckBox 并将其设置为选中真的。

LinearLayout yourLayout= (LinearLayout) view.findViewById(R.id.linearLayout);
int count = yourLayout.getChildCount();
for (int i = 0; i < count; i++) {
    View v = rootLinearLayout.getChildAt(i);
    if (v instanceof CheckBox) {
        ((CheckBox) v).setChecked(true);
    }
}

我希望这会有所帮助

于 2017-08-28T11:30:42.750 回答
1

如果CheckBoxes以编程方式添加,您可以在Activity类的成员变量中保存对它们的引用。

于 2012-08-17T07:26:46.050 回答