You should override getView
method in your listview adapter from which you can do the following :
View getView (int position, View convertView, ViewGroup parent) {
...
if(position % 2 == 0) {
convertView.setBackgroundColor(color1);
else {
convertView.setBackgroundColor(color2);
}
return convertView;
}
Of course your convertView should have been created before. If your adapter just extends ArrayAdapter
you can just add the following line instead of the dots :
convertView = super.getView(position, convertView, parent);
Checkout this tutorial for more information.
EDIT
I will explain a little bit more.
When you want to use a ListView, you need an Adapter. The adapter is used to render the data, so each row. The ListView is just the container of the row, so if you change the background color of the ListView, you are just changing the color of the whole container. What you want to do is changing the color of each row. You have to do it in the adatper's method getView
.
So first you extend for exemple an ArrayAdatper and you override getView
public class MyAdatper extends ArrayAdapter<String> {
View getView (int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
if(position % 2 == 0) {
convertView.setBackgroundColor(color1);
else {
convertView.setBackgroundColor(color2);
}
return convertView;
}
Then in your Activity you do :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
resultListView = (ListView)findViewById(R.id.efile_results_list_view);
String[] mockValue = {
"Value 1",
"value 2",
"value 3" };
MyAdatper adapter = new MyAdapter(this, R.layout.list_item, R.id.info_text, mockValues));
resultListView.setAdapter(adapter);
}
Finally, create a layout that will represent a row. For example inside list_item.xml
:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_gravity="center"
android:layout_margin="10dp">
<TextView
android:id="@+id/info_text"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
I suggest that you look at some documentation and some tutorial to know exactly how this is working.
Here I gave you the example for a simple ListView Displaying an Array of String. If you are looking to display more complex views, look for the BaseAdapter.