In Android development, if you want to add a listener event to a button, there are three ways to implement it.
1, the way one
Public classMainactivity extends Actionbaractivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); //Get button ButtonsButton btncall=(Button) Findviewbyid (R.id.btncall); //to add a listener event for the button buttonsBtncall.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubCall (); } }); } /** * Method*/ Public voidCall () {System. out. println ("Make a phone call"); }}
2, Mode two
Public classMainActivity2 extends Actionbaractivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); //Find buttonButton Btncall =(Button) Findviewbyid (R.id.btncall); //Monitor events for button ButtonsBtncall.setonclicklistener (NewMyonclicklisten ()); } /** * is the class that implements Onclicklistener * * @author Administrator **/ classMyonclicklisten implements Onclicklistener {@Override Public voidOnClick (View v) {//TODO auto-generated Method StubCall (); } } /** * Method*/ Public voidCall () {System. out. println ("Make a phone call"); }}
3, Mode three
Public classMainActivity3 extends Actionbaractivity implements Onclicklistener//To implement Oncicklistener this interface {@Overrideprotected voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); //Find the buttonButton btncall=(Button) Findviewbyid (R.id.btncall); //button Set Listener eventBtncall.setonclicklistener ( This); } //Method Public voidCall () {System. out. println ("Make a phone call"); } //implementing methods in the Onclicklistenr interface@Override Public voidOnClick (View v) {//TODO auto-generated Method StubCall (); }}
Android to add listener events to the button