Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List items with alternating colors

I have a list view and an adapter that sets alternating background colors to the list items ("zebra" list style):

public View getView(final int position, View convertView, ViewGroup parent) {
    int colorPos = position % colors.length;
    ...
    convertView.setBackgroundColor(colors[colorPos]);
    return convertView;
}

But now, when i select an item using scroll wheel, or when I click an item, the original colors for selecting/clicking do not override my custom backgrounds (I can see the original color below the one I set).

How can I set the original colors for these states?

like image 403
zorglub76 Avatar asked Jan 12 '10 16:01

zorglub76


1 Answers

I think the easiest way is to create two selectors which are used as the background resources, with transparent color in the state_selected mode: (res/drawable/alterselector1.xml:)

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

</selector>

(res/drawable/alterselector2.xml:)

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

(res/values/colors.xml:)

<resources>
    <drawable name="transparent">#00ffffff</drawable>
    <drawable name="altercolor1">#ffffffff</drawable>
    <drawable name="altercolor2">#ff000000</drawable>
</resources>

Then you set the backgrounds in the getView method of the adapter with the setBackgroundResource method:

if (position % 2 == 0){
    reusableView.setBackgroundResource(R.drawable.alterselector1);
} else {
    reusableView.setBackgroundResource(R.drawable.alterselector2);
}

Now when you select a row, your background don't hide the original selector behind.

like image 174
Utyi Avatar answered Jan 04 '23 04:01

Utyi