friend ,
我正在尝试编写一个在 ChildView 中使用单选复选框的 ExpandableListView。 而且我无法理解如何在 ExpandableListView 的 OnChildClickListener() 中将其他 CheckBox 设置为“false”。这是我的代码:
ExpListView.setOnChildClickListener(new OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
CheckBox cb = (CheckBox) v.findViewById(R.id.checkbox);
if (cb.isChecked()) {
} else {
cb.setChecked(true);
//Here somehow I must set all other checkboxes to false.
//Is it possible?
}
return false;
}
});
这是 ChildView 的 xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="@+id/textChild"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textColor="@android:color/white"
android:layout_weight="1"
/>
<CheckBox android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:clickable="false"
android:layout_gravity="right"
android:visibility="visible"
/>
</LinearLayout>
最佳答案
如果您只想选择一个复选框,您可以将选中的复选框存储在一个变量中 CheckBox checkedBox;
.当 CheckBox
被点击,你可以按照
@Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
CheckBox last = checkedBox //Defined as a field in the adapter/fragment
CheckBox current = (CheckBox) v.findViewById(R.id.checkbox);
last.setCheked(false); //Unchecks previous, checks current
current.setChecked(true); // and swaps the variable, making
checkedBox = current; // the recently clicked `checkedBox`
return false;
}
不过,我不确定这是否适用于 Android 的 View 回收系统,但值得一试。
如果需要多选,可以展开checkedBox
进入List<CheckBox>
,并在每次需要取消选中框时对其进行迭代。
如果你需要存储一些额外的数据(你很可能需要),你可以创建一个 holder 类,例如
class CheckBoxHolder{
private CheckBox checkBox:
private int id;
public CheckBoxHolder(CheckBox cb, int id){
this.checkBox = cb;
this.id = id;
}
// Getter and/or setter, etc.
}
关于Android ExpandableListView 在 ChildView 有单选 CheckBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19293903/