Creating an Alternate-Colored List View in Android

This post will help you make a list with alternate row in different colors. This is What your list will look like:

To accomplish this, first of all create a layout file and add a listview in it. We name this file “categories.xml“:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/RelativeLayout1">
    <ListView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/listView1" />

Next, you need to create an activity. Let’s name this file “” and enter following code in oncreate() method:

ListView listView = (ListView) findViewById(;
listView.setAdapter(new CategoriesListAdapter(this));

Next step it to create create a custom adapter for our list. In our code above, we’ve named it CategoriesListAdapter. Extend this class from BaseAdapter and implement the methods as usual.

Now, in, we’ll first declare and initialize a list of colors:

public class CategoriesListAdapter extends BaseAdapter {
    private final int[] bgColors = new int[] { R.color.list_bg_1, R.color.list_bg_2 };

You have to define these colors in an xml file e.g., colors.xml under res/color. Alternatively, you can use Android’s built-in colors like Color.YELLOW or Color.BLUE for which you don’t need to define these colors. But if you select the first method, your colors.xml will look like this:

<?xml version="1.0" encoding="utf-8"?>
    <color name="list_bg_1">#ffffff</color>
    <color name="list_bg_2">#fef2e8</color>

Now the last step is to set these colors in getView() method. Use the following code snippet for this:

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.item_categorylist, null);
        holder = new CategoryContentsHolder();
        holder.title = (TextView) convertView.findViewById(;
    } else
        holder = (CategoryContentsHolder) convertView.getTag();
        int colorPosition = position % bgColors.length;
        if (holder != null) {
        return convertView;

class CategoryContentsHolder {
    TextView title;

That was all! The same way you can create a list with 3 or more color.