[Learn Android while working on projects] mobile security guard 08-layout and display details: State List, android08-
We noticed that the display status of buttons in some applications is different from that of normal ones when they are clicked, for example:
Normal: selected:
How can this effect be achieved? The Android system provides us with a convenient method to implement this function: state list drawable.
StateListDrawableIt is a drawable object defined in XML. We can set images under different items to display different States, depending on the status of the drawable object. For example, a Button control can have different States (click, focus, etc.), and provide different background images for different States through a series of drawable objects.
You can use an xml file to describe the status sequence.<selector>
Element<item>
Element to represent each background, where each<item>
Different attribute values can be used to describe a status.
When the status changes, the status list is scanned from top to bottom, and the first image matching the current status is used. This selection is not based on the best match, but simply selects the first project that meets the conditions.
Its XML file is defined as follows:
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" android:constantSize=["true" | "false"] android:dither=["true" | "false"] android:variablePadding=["true" | "false"] > <item android:drawable="@[package:]drawable/drawable_resource" android:state_pressed=["true" | "false"] android:state_focused=["true" | "false"] android:state_hovered=["true" | "false"] android:state_selected=["true" | "false"] android:state_checkable=["true" | "false"] android:state_checked=["true" | "false"] android:state_enabled=["true" | "false"] android:state_activated=["true" | "false"] android:state_window_focused=["true" | "false"] /></selector>
1. Create your own. xml file in the/res/drawable directory, for example, button_selector.xml.
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" > <item android:state_enabled="true" android:state_window_focused="false" android:drawable="@drawable/button_background"/> <item android:state_pressed="true" android:state_window_focused="true" android:drawable="@drawable/button_background_selected"/> <item android:state_focused="true" android:drawable="@drawable/button_background"/> <item android:drawable="@drawable/button_background"/></selector>
2. Reference in the layout xml file:
<Button android: id = "@ + id/bt_first_dialog_confirm" android: layout_width = "140dip" android: layout_height = "40dip" android: background = "@ drawable/button_selector" android: text = "OK" android: textColor = "# ffffffff"/>
At the same time, we can also set the effect when the GridView neutron control is clicked. I will not go into details here.