vijay

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, R.id.label, str);
              lst.setAdapter(adapter);

First step:
Create one separate class file and then extends the adapter that you used. Here I am using arrayadpater
And create class name BEadapter.java
Code:
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
       }
      
       @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;
       }

}

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

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 …..

0 comments:

Post a Comment