Showing posts with label custom adapter. Show all posts
Showing posts with label custom adapter. Show all posts

Tuesday, July 5, 2011

Android List view with alternating row colors

In this article, we shall see how to apply alternating row colors to a listview.

Steps:
  • Create your own Adapter and override getView method.
  • Use your own logic and set background color inside the getview method.
Source Code


/**
*
*/
package com.blogs.adapters;

import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.SimpleCursorAdapter;

/**
* @author C'dine
* A simple cursor adapter. Only variation is that it displays alternate rows
* in alternate colors.
*/
public class AlternateRowCursorAdapter extends SimpleCursorAdapter{

private int[] colors = new int[] { Color.parseColor("#F0F0F0"), Color.parseColor("#D2E4FC") };
//private int[] colors = new int[] { R., 0x30808080 };
public AlternateRowCursorAdapter(Context context, int layout, Cursor c,
String[] from, int[] to) {
super(context, layout, c, from, to);
}
/**
* Display rows in alternating colors
*/
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
int colorPos = position % colors.length;
view.setBackgroundColor(colors[colorPos]);
return view;
}
}


Output: