【问题标题】:ExpandableListView child item's CheckBox gets checked randomlyExpandableListView 子项的 CheckBox 被随机检查
【发布时间】:2013-09-05 13:22:43
【问题描述】:

我创建了一个带有相当复杂的子项 xml 的 ExpandableListView。它包含一个 TextView、一个 Checkbox 和一个 EditText。 这是 CheckBox 部分:

 <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
               android:layout_width="match_parent"
               android:layout_height="55dip"
               android:orientation="horizontal"
               android:stretchColumns="0">
  <TableRow>
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  >
  <TextView
      android:id="@+id/lblListItem"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:textSize="14dip"
      android:paddingTop="2dp"
      android:paddingBottom="2dp"
      android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft"/>
  <CheckBox
      android:id="@+id/cboxIsRel"
      android:layout_width="wrap_content"
            android:layout_height="wrap_content">

  </CheckBox>
  </TableRow>
  </TableLayout>

如果我检查第 1 项,则在每个组中,也会检查第 5 项(如果选择了第 2 项,则选择第 6 项)。

为什么他们也会被选中?

更新:

getChildView 方法中我有这个代码:

if (convertView == null)
{
  LayoutInflater infalInflater = (LayoutInflater) this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  convertView = infalInflater.inflate(R.layout.expandable_list_item, null);
}
TextView txtListChild = (TextView) convertView.findViewById(R.id.lblListItem);
txtListChild.setText(childText);

如果我不使用 convertView 检查,则不会重复使用该复选框,但如果我滚动出去,选定的复选框也会被取消选中。

【问题讨论】:

    标签: android android-layout expandablelistview


    【解决方案1】:

    这是因为视图的回收。

    确保在您的适配器上,bindView() 或 getView() 方法将复选框设置为选中或不选中。

    编辑:

    ListView 重用视图以提高性能,因此在您的情况下,检查第一个项目,然后在第 5 个子项上使用相同的视图,所以它也被检查。

    因此,为防止这种情况发生,您必须保存选中的位置,并在 getChildView() 方法中根据保存的值选中/取消选中复选框。

    这样,您检查第 1 个项目,然后滚动并将视图回收到第 5 个孩子,适配器将为位置 5 调用 getChildView 并且您将检查它是否被检查。由于未选中,因此您在复选框上调用 setchecked(false) 它将显示为未选中。

    【讨论】:

    • 我不太明白你的提议。在适配器中,我有一个 getChildView,但它没有设置任何复选框的状态。你能再解释一下吗?
    • 我有责任保存复选框的选中状态吗?比如说,在 HashMap 中?没有任何内置支持吗?
    • 嗯,这就是列表视图需要适配器的原因。适配器是要显示的数据的表示。如您所见,复选框保持其状态,这就是您遇到问题的原因。我不明白你为什么不保存这些信息,你不能依赖你的活动永远留在内存中,你需要保存你的数据以在活动被销毁时返回到最后一个状态。
    • 感谢您的解释。我会保存状态并恢复它们。
    猜你喜欢
    • 2016-03-18
    • 2012-01-15
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    相关资源
    最近更新 更多