【发布时间】:2023-03-21 09:35:01
【问题描述】:
我创建了一个带有复选框和两行文本的自定义列表视图。我想在单击列表项时更改复选框状态(这意味着如果单击列表项复选框或文本的任何部分,复选框将更改状态)。 为了实现这一点,我在 custom_list_row xml 文件中添加了这个:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants" >
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:clickable="false" />
在 java 类中我做了这些:
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final CheckBox checkBox;
checkBox = (CheckBox)view.findViewById(R.id.checkbox);
if(checkBox.isChecked()){
checkBox.setChecked(false);
}
else {
checkBox.setChecked(true);
}
}
});
这很好用。但唯一的问题是,当我选择一些项目并向下滚动时-->返回所选项目-->所选项目变为未选中。
我没有对 setOnCheckedChangeListener 做任何事情
出了什么问题?任何解决此问题的建议都会有所帮助。
谢谢
【问题讨论】:
-
你需要为此维护布尔数组
-
你的意思是我必须创建一个数组来保存所有复选框的状态吗?
-
是的,但是尝试使用recyclerview
-
与视图无关。只需为所有复选框的状态创建一个 ArrayList。然后在列表视图的单击中将它们的值添加到列表中。在您的适配器中使用该列表后,例如 checkBox.setChecked(arrayList.get(position));