Android ListView Highlight Selected Row



I am trying to highlight the selected row of items from listview. Here is how I set up my listview:



public void buildCatListView(){
//Code to get data from database

}
// Set the data into listview
catlistview.setAdapter(new ListAdapter(this));

catlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id) {

// Get the transaction record ID
categoryID = _catlist.get(position)
.getCategoryID();

for (int j = 0; j < parent.getChildCount(); j++)
parent.getChildAt(j).setBackgroundColor(Color.WHITE);
// Change the background color of the selected element
item.setBackgroundColor(Color.rgb(246, 206, 206));
}
});
mDbHelper.close();
}


And the XML file of my list view:



<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>


And the XML file of my list view row:



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://ift.tt/nIICcg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp">

<TextView
android:id="@+id/txtDisplayCat"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="15dp" />

<TextView
android:id="@+id/txtDisplayCatDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="10dp" />

</LinearLayout>


It did highlight the selected row when clicked. But it behaved in a very weird way. Let's say I selected the first item, it's not only highlighting the first item but also the last. Then when I scroll down, the highlighted row sometimes will shift to second or third. I not sure why is it so.


Just wonder is there any alternate way to do this?


Thanks in advance.


No comments:

Post a Comment