我的XML布局中有n个CheckBox元素用于用户注册页面。我的XML如下:
<CheckBox
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1"/>
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2" />
如何在我的java代码中将这些元素添加到CheckBox类型的LinkedList中?理想情况下,我想使用for循环查找包含ID&#34;复选框的所有元素。&#34;
感谢您的帮助。
答案 0 :(得分:2)
您可以遍历父视图(假设它被称为resultView
)。
List<CheckBox> boxes = new ArrayList<>();
for (int i = 0; i < resultView.getChildCount(); i++) {
if (resultView.getChildAt(i) instanceof CheckBox) {
// this is a check box for sure
boxes.add((CheckBox) resultView.getChildAt(i));
}
if (resultView.getChildAt(i).toString().contains("checkbox")) {
// this might be a checkbox, and may cause ClassCastException
boxes.add((CheckBox) resultView.getChildAt(i));
}
}
答案 1 :(得分:1)
如果您的CheckBox在同一个父视图中,您可以尝试为其子项循环,如:
List<CheckBox> list = new LinkedList<>();
RelativeLayout layout = (RelativeLayout)findViewById(R.id.layout);
for (int i = 0; i < layout.getChildCount(); i++) {
View child = layout.getChildAt(i);
//Some condition to get the view you want
//and make sure it's a CheckBox (maybe by tag?)
list.add((CheckBox)child);
}