Android implementation button click effect (first click color change, second recovery), android button
1. Create a button
<Button
Android: id = "@ + id/click"
Android: layout_width = "fill_parent"
Android: layout_height = "wrap_content"
Android: text = "Click color change"
Android: background = "@ drawable/btn_st"
Android: gravity = "center"/>
2. The background of the button created in 1 uses btn_st and creates btn_st under drawable.
<? Xml version = "1.0" encoding = "UTF-8"?>
<Selector xmlns: android = "http://schemas.android.com/apk/res/android">
<Item android: state_activated = "true" android: drawable = "@ drawable/color1"> </item> <! -- Color when no clicks -->
<Item android: state_activated = "false" android: drawable = "@ drawable/color2"> </item> <! -- Click the color -->
</Selector>
3. Add the color1 and color2 used in 2 to the strings of values.
<Drawable name = "color1" >#339966 </drawable>
<Drawable name = "color2"> # fff </drawable>
4. java code
(1) first obtain the button
Button clickbtn = (Button) findViewById (R. id. click );
(2) Set a flag
Int flag = 0;
(3) Add a listening event to the button
Clickbtn. setOnClickListener (new Button. OnClickListener (){
Public void onClick (View v ){
Switch (flag ){
Case 0:
MBtn [I]. setActivated (false );
Flag = 1;
Break;
Case 1:
MBtn [I]. setActivated (true );
Flag = 0;
Break;
}
}
}
Idea: set two different colors for the button to activate or not activate. When the button is clicked once or three times, the button is set to inactive (pressed). When the button is clicked even times, it is set to active (not pressed ).