Android - ListView,为什么 list.getChildAt(2).findViewById(R.id.icon) return 多个

Android - ListView, why does list.getChildAt(2).findViewById(R.id.icon) return multiple

我在使用 android ListView 和 GridView

时遇到了一个奇怪的问题

我有一个包含 100 个项目的 ListView,这个 xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:id="@+id/main_screen">
  <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
      android:id="@+id/name"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
    <ImageView
      android:id="@+id/icon"
      android:layout_width="40dp"
      android:layout_height="40dp"
      android:src="@drawable/icon_1"
      android:onClick="changeIcon" />
  </RelativeLayout>
</RelativeLayout>

public void changeIcon(View view) {
    ImageView myIcon= (ImageView)view.findViewById(R.id.icon);
    myIcon.setImageResource(R.drawable.icon_2);
}

如果我单击列表中的第一个图标,它确实会替换我触摸的图标(这是我想要的),但是,它也会替换视图之外的图标,不是全部,而是它顺序发生..

所以在图片中,1 是我触摸选择的,13,25,37 等..是自动选择的.. 当我快速向上滚动时,#1 上的图标会随机变化。有时它会转到#2 或#3..

同样的问题发生在 GridView 上..

任何人都可以解释这种行为吗?我该怎么做才能避免这种情况。

Link 截图: http://imgur.com/a/5pFMA

图片 1 为空列表, 图 2 是我点击图标 #1, 图 3 显示 13 也因我触摸 #1 而改变,

问题是 ListView 在滚动后会重新使用视图。

您应该单独保存每个列表项的状态。这应该在自定义适配器中完成。