2

我的应用程序有一个调查表,通过 listView 显示。用户可以通过单击 ListItem 来回答真假。一个 imageView 表明答案是正确的。(每次单击 ListItem 时我都会更改 imageView)

在全球范围内它工作正常。我已经能够动态地更改 imageView,但令人惊讶的是,当我使用setImageResource时,图像会在几行上发生变化。 例如,如果我单击第 2 行(索引 1),图像会在第 2 行发生变化,但也会在第 12 行和第 22 行发生变化。

目前我还没有找到解决方案。如果您对我有任何线索,我将不胜感激。

这是我的列表项的布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="30dp"
 >

<ImageView
    android:id="@+id/ivCheck"
    android:layout_width="25dp"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical"
    android:contentDescription="selection state"
    android:src="@drawable/check_grey" />


<TextView
android:id="@+id/tvId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textIsSelectable="false"
android:layout_gravity="center_vertical"
android:text="dummy text"
android:visibility="gone"
/>

<TextView
    android:id="@+id/tvText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_gravity="center_vertical"
    android:layout_marginLeft="14dp"
    android:layout_toRightOf="@+id/ivCheck"
    android:text="dummy text"
    android:textIsSelectable="false" />

</RelativeLayout>

这是我更改图像的方法(在 listActivity 中)

protected void onListItemClick(ListView l, View v, int position, long id) {     
ImageView image = (ImageView)v.findViewById(R.id.ivCheck);
QuizAnswer currentQuizAnswer = (QuizAnswer) quizRequest.getListAnswers().get(position);
if(currentQuizAnswer.isSelected()) {
    image.setImageResource(R.drawable.check_grey);
} else {
    image.setImageResource(R.drawable.check_green);
}
currentQuizAnswer.setSelected(!currentQuizAnswer.isSelected());
}

提前感谢您的帮助

4

3 回答 3

0

It is due to views' recycling in ListView. You need to override getView method of your adapter and reset the source for your ImageViews which does not relate with the previous change.

For more info, read this or watch this video.

于 2013-04-29T12:39:29.660 回答
0

You will have to apply custom adapter to the listview. Check these links:

Link 1 Link 2 Link 3 Link 4. Hope this will prove helpful to you. Also have a look at The world of listview. Your doubts will definitely be solved, such a nice tutorial this is.

于 2013-04-29T13:16:43.573 回答
0

改变单行,看看神奇

position = position % (QuizAnswer) quizRequest.getListAnswers().size();
于 2013-04-29T12:59:20.577 回答