We often use button buttons on the interface, but usually button click to see the effect of the click, if the user clicks two consecutive times, will report NAR error, so the interactivity is relatively poor. If we customize the button click Effect, for example, if we click on the button, we can see that we did click the button, which effectively avoids repeated clicks.
There are two ways to customize the Click Effect, one in XML and the other in code.
First look at how to define in XML:
Create a new Selector.xml file under drawable:
<?xml version= "1.0" encoding= "Utf-8"?> <selector xmlns:android=
"http://schemas.android.com/apk/res/" Android >
<item android:drawable= "@drawable/button_press" android:state_pressed= "true"/>
< Item android:drawable= "@drawable/button_nomal" android:state_focused= "false" android:state_pressed= "false"/>
<item android:drawable= "@drawable/button_focus" android:state_focused= "true"/>
<item android: drawable= "@drawable/button_nomal" android:state_focused= "false"/>
</selector>
Two states are defined: one is to get the focus by pressing the next one.
Drawable each of these three photos.
Then add button buttons under Main.xml
<button
android:id= "@+id/button1"
android:layout_width= "Wrap_content"
Wrap_content "
android:text=" button effect Demo "
android:background=" @drawable/selector "/>
Get the button in the Mainactivtiy
Button button1= (button) This.findviewbyid (r.id.button1);
Button1.setonclicklistener (New View.onclicklistener () {
@Override public
void OnClick (View v) {
//TODO auto-generated method Stub
Toast.maketext (Getapplicationcontext (), "You clicked the button button", Toast.length_short). Show () ;
}
});
Below look at the Click Effect:
Before clicking button:
When the button is pressed:
Next, look at the second implementation, implemented in code:
First, add in Main.xml:
<button
android:id= "@+id/button2"
android:layout_width= "Wrap_content"
Wrap_content "
android:text=" button effect Demo "
android:background=" @drawable/button_nomal "/>
The following is implemented in Mainactivity:
Button button2= (button) This.findviewbyid (r.id.button2);
Button2.setontouchlistener (New Ontouchlistener () {
@Override public
boolean Ontouch (View V, motionevent event {
//TODO auto-generated method Stub
if (Event.getaction () ==motionevent.action_down) {
V.setbackgroundresource (r.drawable.button_press);
} else if (event.getaction () ==motionevent.action_up) {
v.setbackgroundresource (r.drawable.button_nomal);
}
return false;
}
});
In this class the Ontouchlistener of the button is monitored, because the onclicklistener inherits the Ontouchlistener. The effect is the same as above, there is no explanation here.
The above is the Android custom button click Effect to achieve the full content of the way, I hope to give you a reference, but also hope that we support the cloud habitat community.