In a development application, in many cases, to design the background of a ListView or button control, the following is a summary of the use of Android's selector:
1. Configure the Android selector in the drawable.
Save the following XML file as your own named. xml file (such as Item_bg.xml) and place the file in the drawable file, using the background image according to the status of the list items in the ListView when the system is in use.
Copy Code code as follows:
<?xml version= "1.0" encoding= "Utf-8"?>
<selector xmlns:android= "Http://schemas.android.com/apk/res/android" >
<!--The default background picture-->
<item android:drawable= "@drawable/pic1"/>
<!--background picture without focus-->
<item android:state_window_focused= "false" android:drawable= "@drawable/pic1"/>
< background picture--> when you get focus and click in non-touch mode!--
<item android:state_focused= "true" android:state_pressed= "true"
android:drawable= "@drawable/pic2"/>
<!--background picture when clicked in touch mode-->
<item android:state_focused= "false" android:state_pressed= "true"
android:drawable= "@drawable/pic3"/>
< picture background When selected!---->
<item android:state_selected= "true" android:drawable= "@drawable/pic4"/>
<!--picture background When the focus is obtained-->
<item android:state_focused= "true" android:drawable= "@drawable/pic5"/>
</selector>
2. Use the above configuration file:
The first method is configured in the ListView configuration file with the following code: android:listselector= "@drawable/item_bg"
The second method is to add attributes to the ListView item, which is as follows: android:background= "@drawable/item_bg"
The third way is to set the code in Java code as follows: Drawable drawable =getresources (). getdrawable (R.DRAWABLE.ITEM_BG);
Listview.setselector (drawable);
The above setting method shows that the effect is sometimes black, so you need to add the following code to the configuration file: android:cachecolorhint= "@android: Color/transparent" to make the background transparent.
Similarly, the button has some background effects, which are explained by attributes:
Android:state_selected is the effect of setting a check
Android:state_focused is the effect of setting the focus
Android:state_pressed is the effect of setting the click
Android:state_enabled is setting whether to respond to events
Here is a selector to set the state of the text in the button, as follows:
Copy Code code as follows:
<?xmlversion= "1.0" encoding= "Utf-8"?>
<selectorxmlns:android= "Http://schemas.android.com/apk/res/android" >
<itemandroid:state_selected= "true" android:color= "#FFF"/>
<itemandroid:state_focused= "true" android:color= "#FFF"/>
<itemandroid:state_pressed= "true" android:color= "#FFF"/>
<itemandroid:color= "#000"/>
</selector>