Reputation: 6487
I am trying to change the background color in my listview whenever any item on the list is clicked.
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos,
long arg3) {
listView.getChildAt(pos).setBackgroundResource(R.color.GREY);
}
});
However, this piece of code is not working as expected. Its behaving erratically. Sometimes, its changing background of two items at once and if i drag my list down, an already changed color item is resetting.
Can anyone help me here?
Thx! Rahul
Upvotes: 0
Views: 516
Reputation: 12134
Use this in code,
put this xml file in drawable folder(you will change the colors as your wish).
listselector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize="true">
<item android:state_focused="false" android:state_pressed="false">
<shape android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
<stroke android:width="2dp" android:color="@android:color/transparent" />
<padding android:left="1dp" android:top="1dp" android:right="1dp"
android:bottom="1dp" />
</shape>
</item>
<item android:state_focused="true" android:state_pressed="false">
<shape android:shape="rectangle">
<solid android:color="@color/listitemfocus"/>
<stroke android:width="4dp" android:color="@android:color/transparent" />
<padding android:left="1dp" android:top="1dp" android:right="1dp"
android:bottom="1dp" />
</shape>
</item>
<item android:state_pressed="true">
<shape android:shape="rectangle">
<solid android:color="@color/listitempress"/>
<stroke android:width="4dp" android:color="@android:color/transparent" />
<padding android:left="1dp" android:top="1dp" android:right="1dp"
android:bottom="1dp" />
</shape>
</item>
</selector>
in your main layout use listview with android:listSelector:
<ListView
android:id="@+id/listView1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_below="@+id/parent_image_view"
android:layout_centerHorizontal="true"
android:cacheColorHint="@android:color/transparent"
android:listSelector="@drawable/listselector"
android:scrollbars="none" />
Upvotes: 1
Reputation: 8079
This is happening because the items of a list view(Rows) will be recycled for performance improvement...if a view is not in screen.. then instead of creating a new view for next element.. previous view is showed with new content... so you should keep track of the items for which you are changing the colour... You can see this example... I think it helps... there he is using a viewholder class.. to manage the data.. u can put a variable for colcour also.. and check the background colour..of an item..
Upvotes: 0