Android ListView's item background color settings, androidlistview
1. How to change the background color and press the color of the item
By default, the background color of an item is black and the color is yellow when you click it. To change to a custom background color, there are three methods:
1) set listSelector
2) set the background of the item in the layout File
3) set it in getview of the adapter.
All three methods can change the default background color and press color of the item. We will explain them separately, but before that, we need to write the selector. xml file;
<?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>
Selector can be used to change the default background color of a button or listview item. Drawable can be set as a color resource or an image resource.
1) set listSelector of listview
<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) set the background attribute in the layout file of listitem. below is the layout file of 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 = "History" android: textColor = "# ffffff" android: textSize = "20sp" android: layout_centerInParent = "true"> </TextView> </RelativeLayout>
3) In the getView method of the adapter, Set
if(convertView ==null) { convertView = LayoutInflater.from(context).inflate(R.layout.listitem, null); } convertView.setBackgroundResource(R.drawable.selector);
The above methods can achieve the same effect, that is, to change the default background color of the item and the background color when you click it. The third method is the most flexible, if the odd and even rows of listview need to be set to different selector, only the third method can be used.