Rami Loiferman Rami Loiferman - 1 year ago 94
Java Question

How to color selected item of ListView on android at onListItemClick method

I know that familiar question exist my is a little different.
I'm implementing ListView on android.
This method should color item when it clicked.

protected void onListItemClick(ListView l, View v, int position, longid) {
super.onListItemClick(l, v, position, id);
Language lng = lng.get(position);

My problem is that when i click on item some other items are get colored to.
why is that happens?

Answer Source

why is that happens?

Its happen because of ListView's recycling mechanism.

And is there a difference between l.getChildAt(position) to view v itself ?


To solve your problem, i suggest you to use a Selector to change rows color depending on state.


1) Create a selector xml file: listview_selector.xml

 <?xml version="1.0" encoding="utf-8"?>

    <selector xmlns:android="http://schemas.android.com/apk/res/android" >

        android:drawable="@drawable/listview_selector_focused" />

        android:drawable="@drawable/listview_selector_pressed" />


2) Add the selector to your ListView:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download