1新建两个背景Drawable
even_row.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#A0A0A0"/>
<padding android:left="3dp" android:top="3dp" android:right="3dp" android:bottom="3dp" />
<stroke android:width="1dp" android:color="#00CC00"/>
</shape>
odd_row.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="#A0A0A0"/>
<padding android:left="3dp" android:top="3dp" android:right="3dp" android:bottom="3dp" />
<stroke android:width="1dp" android:color="#00CC00"/>
</shape>
2创建两个selectors
listview_selector_event.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/even_row" android:state_enabled="true"/>
<item android:drawable="@drawable/even_row" android:state_pressed="true"/>
<item android:drawable="@drawable/even_row" android:state_focused="true"/>
</selector>
listview_selector_odd.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/odd_row" android:state_enabled="true"/>
<item android:drawable="@drawable/odd_row" android:state_pressed="true"/>
<item android:drawable="@drawable/odd_row" android:state_focused="true"/>
</selector>
3 有了这两个selector就可以把我们背景资源添加到listview上了。
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
PlanetHolder holder = new PlanetHolder();
// First let's verify the convertView is not null
if (convertView == null) {
// This a new view we inflate the new layout
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.row_layout, null);
// Now we can fill the layout with the right values
TextView tv = (TextView) v.findViewById(R.id.name);
holder.planetNameView = tv;
v.setTag(holder);
if ( position % 2 == 0)
v.setBackgroundResource(R.drawable.listview_selector_even);
else
v.setBackgroundResource(R.drawable.listview_selector_odd);
}
else
holder = (PlanetHolder) v.getTag();
Planet p = planetList.get(position);
holder.planetNameView.setText(p.getName());
return v;
}