Android ListView with alternate color and on focus color

12,514

Solution 1

I found this tutorial to be very helpful for me.

http://ykyuen.wordpress.com/2010/03/15/android-%E2%80%93-applying-alternate-row-color-in-listview-with-simpleadapter/

I was able to make the ListView items have alternating colors plus the focused item kept the default highlighted color.

Solution 2

Put a transparency in your color, the yellow highlighting is still there, it is just behind your background color, a transparency will let it show through.

Share:
12,514
Yogesh
Author by

Yogesh

Updated on November 19, 2022

Comments

  • Yogesh
    Yogesh over 1 year

    I need to set alternate color in list view rows but when i do that it removes/ disables the on focus default yellow background

    I tried with backgroundColor rowView.setBackgroundColor(SOME COLOR);

    also with backgrounddrwable.

    rowView.setBackgroundColor(R.drawable.view_odd_row_bg);
    
    <?xml version="1.0" encoding="utf-8"?>
    <selector
       xmlns:android="http://schemas.android.com/apk/res/android">
       <item
          android:state_window_focused="false"
          android:drawable="@color/odd" />
    
       <!--
          Even though these two point to the same resource, have two states
          so the drawable will invalidate itself when coming out of pressed
          state.
       -->
       <item
          android:state_focused="true"
          android:state_enabled="false"
          android:state_pressed="true"
          android:drawable="@color/highlight" />
       <item
          android:state_focused="true"
          android:state_enabled="false"
          android:drawable="@color/highlight" />
    
       <item
          android:state_focused="true"
          android:state_pressed="true"
          android:drawable="@color/highlight" />
       <item
          android:state_focused="false"
          android:state_pressed="true"
          android:drawable="@color/highlight" />
    
       <item
          android:state_focused="true"
          android:drawable="@color/highlight" />
    
    </selector>
    

    but it wont work.

    is there any way we can set background color and on focus color simultaneously which will work.

  • Admin
    Admin almost 14 years
    How can i do that using bindView? I've tried something like this: int i = 0; view.setBackgroundResource(i%2==0 ? R.drawable.bindview_bg_gray : R.drawable.bindview_bg_white); i++; but after a few scrolls it gets all messy!
  • benvd
    benvd over 13 years
    Extremely late comment, but for posterity: Philipz is relying on sequential calling of bindView, which you just should not do. Never assume anything about the order of bindView calls. Instead try to do the modulo operation on cursor.getPosition() (cursor being one of the params of the bindView method).