1新建兩個背景Drawableandroid
even_row.xml3d
<?xml version="1.0" encoding="utf-8"?>xml
<shape xmlns:android="http://schemas.android.com/apk/res/android" >utf-8
<solid android:color="#A0A0A0"/>資源
<padding android:left="3dp" android:top="3dp" android:right="3dp" android:bottom="3dp" />get
<stroke android:width="1dp" android:color="#00CC00"/>it
</shape>io
odd_row.xmlevent
<?xml version="1.0" encoding="utf-8"?>sed
<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;
}