I have a listview defined by the following xml. I need to toggle the image in the list during runtime when the user clicks on any row. How can I achieve this? Any help is highly appreciated. Thanks
//list_item.xml
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/play"
android:id="@+id/img"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:id="@+id/txt"
/>
</LinearLayout>
You can locate the item’s
imgview by callingfindViewByIdon the second parameter (which is theViewof the clicked item) within theonItemClickhandler:EDIT: Be aware that Android reuses list item
Viewobjects (also called view recycling), so the toggle state of each item needs to be stored for later use. The toggle state of each item needs to be accessed whenever a list item view is bound to a list item for display.For example, here is working example of an activity that toggles the image of each item on click:
The important parts to study are the
onItemClickcallback and the override ofgetViewinMyArrayAdapter.The
getViewmethod of theAdapterclass is responsible for inflating the item layout. In this example, I call thegetViewmethod of the superclass to initially prepare the item view, but then I make sure to appropriately set the resource ID of the item’simgview:See also: Developing Applications for Android – Gotchas and Quirks