We've done projects that have done more or less a feature like this: When you click on a component, the background of the component changes. Beginners tend to be a way of thinking: set up a listener for the component, and change the state of the component (background image or background color) when the event is heard. Of course, this is completely true, but when the components are particularly large, there are a lot of code to deal with, and it's cumbersome, and Android provides a selector (selector) to change the state of the interface. Let's change a button background to describe its specific usage.
1. Because selector is configured under the Drawable folder, first create a new Android XML file under the Drawable folder
2. Then add the following code in the Button_selector.xml
The background that was pressed
<item android:state_pressed= "true"
android:drawable= "@drawable/cancel_small_click"/>
Background when getting the focus
<item android:state_focused= "true"
android:drawable= "@drawable/cancel_small_unclick"/>
The background when default
<item android:drawable= "@drawable/cancel_small_unclick"/>
3. Finally, there are two ways of using this XML file:
(1) The first type is configured in the component: Android background= "@drawable/button_selector"
(2) The second type is used in code: drawable drawable = Getresources (). getdrawable (R.drawable.button_selector); Button.setselector (drawable)
Note 1: The list setting selector may appear as black, need to add android:cachecolorhint= "@android: Color/transparent"
Note 2:button's selector has other effects.
Android:state_selected is selected
Android:state_focused is gaining focus
Android:state_pressed is click
Android:state_enabled is the set response event, which refers to all events
The selector effect of the button can also be set according to these states. You can also set selector to change the state of text in a button. Here's how to configure the text effect in the button: Drawable/button_font.xml
Of course button can also achieve more complex effects
A companion tour, a free dating site: www.jieberu.com
Push family, free tickets, scenic spots: www.tuituizu.com
The use of Android selector