welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Wednesday, August 22, 2012

How to show alternating row color on ListView in android

Here I would share the code to apply alternative rows colors on listview.In a previous article I wrote to bind or add the data listview, for your information I mention link as below..

As we know very well we can add the data two listview using two methods..First one is create separate class for adapter and another using hash map string we can add the data in the same activity.
If you are using simple adapter in the same activity then you need to add the alternative row color then follow the below method process.
Here I add the data using simple adapter in the same activity now I want to apply the alternative row color.
If you use any adapter either simple or array you can follow the same process..
Previous code:
       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                           R.layout.rowlayout,, str);

First step:
Create one separate class file and then extends the adapter that you used. Here I am using arrayadpater
And create class name
public class BEadapter extends ArrayAdapter{
       private int[] colors = new int[] { 0x30B0E0E5, 0x30FFFFFF };

       public BEadapter(Context context, int resource, int textViewResourceId,
                     String[] objects) {
              super(context, resource, textViewResourceId, objects);
              // TODO Auto-generated constructor stub
       public View getView(int position, View convertView, ViewGroup parent) {
         View view = super.getView(position, convertView, parent);
         int colorPos = position % colors.length;
         return view;


Now you can change the code in main activity:
New Code:
BEadapter adapter = new BEadapter(this,
                           R.layout.rowlayout,, str);

Instead of using array adapter I used the class BEadapter, now its shows the color on the alternative row..
I hope it been useful..
Post your comments …..


Post a Comment