1.如何改變item的背景色和按下顏色
listview默認情況下,item的背景色是黑色,在用戶點擊時是黃色的。如果需要修改為自定義的背景顏色,一般情況下有三種方法:
1)設置listSelector
2)在布局文件中設置item的background
3)在adapter的getview中設置
這三種方法都能達到改變item默認的背景色和按下顏色,下面來分別講解,但是在這之前需要先寫好selector.xml文件;
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@color/light_blue"></item> <item android:state_pressed="false" android:drawable="@color/sgray"></item> </selector>
在改變button或者listview的item默認背景色,就可以用到selector。drawable可以設置為色彩資源,也可以設置為圖片資源。
1)設置listview的listSelector
<ListView android:id="@+id/history_list" android:layout_width="fill_parent" android:layout_height="wrap_content" android:divider="#565C5D" android:dividerHeight="3dp" android:listSelector="@drawable/selector" android:cacheColorHint="@android:color/transparent"> </ListView>
2)在listitem的布局文件中設置background屬性,下面是listitem的布局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/selector"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="歷史記錄" android:textColor="#ffffff" android:textSize="20sp" android:layout_centerInParent="true"> </TextView> </RelativeLayout>
3)在adapter的getView方法中設置
if(convertView ==null) { convertView = LayoutInflater.from(context).inflate(R.layout.listitem, null); } convertView.setBackgroundResource(R.drawable.selector);
上述方法都能達到同樣的效果,就是改變item默認的背景色和點擊時的背景顏色,第三種方法最靈活,如果listview的奇數行和偶數行需要設置為不同的selector,只能用第三種方法。
參考 http://www.cnblogs.com/dolphin0520/p/3383073.html