Button ---- button
Imagebutton ---- image button
Common features:
Can be used as a button to generate a click event.
Differences
1. The button has the text attribute, but imagebutton does not.
2. imagebutton has the src attribute, and the button does not
Onclick event
Both button and imagebutton have an onclick event.
Use their own. setonclicklistener (onclicklistener) method to add a click event.
In fact, all controls have an onclick event.
Several methods for implementing listener events
1. Implementation of anonymous internal classes
2. Implementation of independent classes
3. Interface implementation
Findviewbyid ---- return a view object, which needs to be converted to the corresponding control type.
The following describes the specific implementation of the three methods.
Package COM. example. button; import android. OS. bundle; import android. app. activity; import android. util. log; import android. view. view; import android. view. view. onclicklistener; import android. widget. button; import android. widget. imagebutton; import android. widget. textview; public class mainactivity extends activity implements onclicklistener {private textview TV; private button loginbutton; private imagebutton Imgbt; @ override protected void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. activity_main); TV = (textview) findviewbyid (R. id. textview1);/** 1. initialize the currently required control * 2. Set the listener of the button and click the button to operate through the listener */loginbutton = (button) findviewbyid (R. id. button1);/** 1. Listener events are implemented through anonymous internal Classes */loginbutton. setonclicklistener (New onclicklistener () {@ overridepublic Void onclick (view arg0) {// listen to the button action in the current onclick method TV. settext ("clicked! ") ;}});/** 2. Listener events are implemented through independent Classes */loginbutton = (button) findviewbyid (R. id. button2); loginbutton. setonclicklistener (listener);/** 3. Implement */imgbt = (imagebutton) findviewbyid (R. id. imagebutton1); imgbt. setonclicklistener (this);} onclicklistener listener = new onclicklistener () {@ overridepublic void onclick (view arg0) {TV = (textview) findviewbyid (R. id. textview1); // TV. settext ("an independent listening event is triggered! "); Log. I ("tag", "independent class") ;};@ overridepublic void onclick (view arg0) {log. I ("tag", "implemented through the interface! ");}}
Button and imagebutton