Mohan Timilsina
Mohan Timilsina

Reputation: 500

color changing while clicking the list view

My android code can change the background color into green of the first visible listview items with onClick event but when I scrolled down the listview and try to click the list then the green color does not appear. How to solve this issue any help will be highly appreciated. I have attached my code snippets herewith.

   public void onItemClick( AdapterView<?> parent, View item,   
                                  int position, long id) {



     for(int i=0; i<parent.getChildCount(); i++)
           {
               Log.d("TAG", "Number of times printed");
                if(i == position)
                {
                          parent.getChildAt(position).setBackgroundColor(Color.GREEN);
                         // Log.d("TAG","Green at position :: " + position);

                }
                else
                {
                          parent.getChildAt(i).setBackgroundColor(Color.GRAY);
                }
            }
}  

Upvotes: 0

Views: 994

Answers (2)

Raheel Sadiq
Raheel Sadiq

Reputation: 9867

Define colors in color.xml file in values folder

make xml file with the following code in drawable folder listViewBackground.xml

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_focused="true" 
      android:state_pressed="false" 
      android:drawable="@color/grey" />

<item android:state_focused="true" 
      android:state_pressed="true"
      android:drawable="@color/green"

       />

<item android:state_focused="false" 
      android:state_pressed="true"
      android:drawable="@color/green" />

<item android:drawable="@color/grey" />

and set this file as background for the list item

Upvotes: 1

raghav chopra
raghav chopra

Reputation: 837

instead of

                  parent.getChildAt(position).setBackgroundColor(Color.GREEN);

try this

    parent.getChildAt(position).setBackgroundColor(R.color.orange);

You need to define your color in color.xml in values folder-- vales/color.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <color name="orange">#e68c10</color>
</resources>

and also look for your function try using

public void onListItemClick(ListView parent,View v,int position,long id){}

Upvotes: 0

Related Questions