In the development of applications, the background of listview or button control should be designed in many cases. The following summarizes the usage of Android selector:
1. Configure Android selector in drawable.
Save the following XML file as your own name. XML file (such as item_bg.xml), and place the file in the drawable file. When used by the system, the corresponding background image is used according to the status of the list items in the listview.
<? XML version = "1.0" encoding = "UTF-8"?>
<Selector xmlns: Android = "http://schemas.android.com/apk/res/android">
<! -- Default background image -->
<Item Android: drawable = "@ drawable/pic1"/>
<! -- Background image without focus -->
<Item Android: state_window_focused = "false" Android: drawable = "@ drawable/pic1"/>
<! -- Background image when the focus is obtained in non-touch mode and clicked -->
<Item Android: state_focused = "true" Android: state_pressed = "true"
Android: drawable = "@ drawable/pic2"/>
<! -- Background image when clicked in touch mode -->
<Item Android: state_focused = "false" Android: state_pressed = "true"
Android: drawable = "@ drawable/pic3"/>
<! -- Background of the selected image -->
<Item Android: state_selected = "true" Android: drawable = "@ drawable/pic4"/>
<! -- Background of the image when the focus is obtained -->
<Item Android: state_focused = "true" Android: drawable = "@ drawable/pic5"/>
</Selector>
2. Use the preceding configuration file:
The first method is to configure in the listview configuration file. The Code is as follows: Android: listselector = "@ drawable/item_bg"
The second method is to add attributes to the listview item. The Code is as follows: Android: Background = "@ drawable/item_bg"
The third method is to set in Java code. The Code is as follows: drawable
Drawable = getresources (). getdrawable (R. drawable. item_bg );
Listview. setselector (drawable );
The above setting method sometimes shows a black effect, 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 as follows:
Android: state_selected is used to set the selected effect.
Android: state_focused is set to get the focus Effect
Android: state_pressed: Set the click Effect
Android: state_enabled is used to set whether to respond to events.
The following is a selector used to set the text status in the button. The Code is 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>
Exchange to explore my Sina Weibo: http://weibo.com/tianrui1990