In development applications, in many cases, the background of listview or button controls should be designed. Let’s summarize the usage of Android selector:
1. Configure Android's selector in drawable.
Save the following XML file into a .xml file named by you (such as item_bg.xml), and place the file in the drawable file. When using the system, use the corresponding background image according to the status of the list items in the ListView.
Copy the codeThe code is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:andro>
<!-- The background picture at the default->
<item android:drawable="@drawable/pic1" />
<!-- Background picture when there is no 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 clicking in touch mode-->
<item android:state_focused="false" android:state_pressed="true"
android:drawable="@drawable/pic3" />
<!--Selected picture background-->
<item android:state_selected="true" android:drawable="@drawable/pic4" />
<!--Picture background when gaining focus-->
<item android:state_focused="true" android:drawable="@drawable/pic5" />
</selector>
2. Use the above configuration file:
The first method is to configure it in the listview configuration file, the code is as follows: android:listSelector="@drawable/item_bg"
The second method is to add attributes to the item of the listview, the code is as follows: android:background="@drawable/item_bg"
The third method is to set it in the java code, the code is as follows: Drawable drawable =getResources().getDrawable(.item_bg);
(drawable);
The above setting method sometimes displays black, so you need to add the following code to the configuration file: android:cacheColorHint="@android:color/transparent" to make its background transparent.
Similarly, Button also has some background effects, as follows:
android:state_selected is the effect when selected
android:state_focused is the effect of setting the focus
android:state_pressed is to set the click effect
android:state_enabled is 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:
Copy the codeThe code is as follows:
<?xmlversion="1.0" encoding="utf-8"?>
<selectorxmlns:andro>
<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>