Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change ListView Item background color but keep the default selector style?

I am trying to programmatically set a custom background color in my ListView Adapter but I want to keep the default Listview Selector style from Android.

I am setting the background color using the "SetBacgroundResource" method of my item view.

I am using Android 4.0 and I tried the example from this blog http://daniel-codes.blogspot.co.nz/2010/07/how-to-change-listview-rows-background.html but using this example the selector shows however the unselected background color is not showing.

How can I achieve this in Android 4.0 ICS?

EDIT: Here is the Resource I am using for the List Item background drawable.

<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_window_focused="false" android:state_selected="true" android:drawable="@android:color/transparent" /> 
   <item android:state_selected="true" android:drawable="@android:color/transparent" /> 
   <item android:state_pressed="true" android:state_selected="false" android:drawable="@android:color/transparent" /> 
   <item android:state_selected="false" android:drawable="@color/list_item_first" /> 
</selector>

The code that I am using to set this background drawable is inside the GetView method of my adatapter. The code is:

convertView.setBackgroundResrouce(R.drawable.list_item_dark);
like image 479
startupsmith Avatar asked Nov 04 '12 08:11

startupsmith


2 Answers

Did you try to set the property android:drawSelectorOnTop of your ListView to true ?
You will be able to set a background for your item and to see the item highlighted when pressed.

like image 60
yDelouis Avatar answered Oct 20 '22 19:10

yDelouis


Try write your custom adapter and set rowView BackgroundColor like that(if position odd number BLACK, even RED). also you can send a color list to adapter and set different color for every rowView

public View getView(int position, View convertView, ViewGroup parent) {
            View rowView = convertView;
        enter code here

            if(rowView == null)
            {
                if((position % 2)==1){ 
                rowView.setBackgroundColor(Color.BLACK)
                    //colorList :setBackgroundColor( colorList.get(position) )
                }
                 else{
                    rowView.setBackgroundColor(Color.RED)
                }
             }           
            return rowView;
        }
like image 44
KEYSAN Avatar answered Oct 20 '22 18:10

KEYSAN