0

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.

@Override
    protected void onListItemClick(ListView l, View v, int position, longid) {
        super.onListItemClick(l, v, position, id);
        Language lng = lng.get(position);
        l.getChildAt(position).setBackgroundColor(Color.GREEN);
    }

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

Rami Loiferman
  • 853
  • 1
  • 6
  • 22

1 Answers1

1

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 ?

No.


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

eg:

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" >

    <item
        android:state_focused="true"
        android:drawable="@drawable/listview_selector_focused" />

    <item
        android:state_pressed="true"
        android:drawable="@drawable/listview_selector_pressed" />

    </selector>

2) Add the selector to your ListView:

<ListView
   ...
   android:listSelector="@drawable/listview_selector"
/>
Community
  • 1
  • 1
Rami
  • 7,879
  • 12
  • 36
  • 66
  • It should be '@drawable' instead of '@color' when applying in the ListView, if you created the file listview_selector.xml in drawable folder. Worked like a charm, thanks. – Lucas Eduardo Jan 23 '16 at 14:05
  • @LucasEduardo You're welcome! it was a typo, thanks... i've edited my answer. – Rami Jan 23 '16 at 14:32