In Android, there are three ways to increase the number of listeners for a button
1. Anonymous inner class
@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //Loading layout FilesSetcontentview (R.layout.activity_main); //get the buttons in the layoutBTN =(Button) Findviewbyid (R.ID.BTN); //Add anonymous inner class listener for buttonBtn.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View arg0) {//TODO auto-generated Method Stub//Print tip InformationToast.maketext (mainactivity. This, "Anonymous inner class implements listening", Toast.length_short). Show (); } }); }
2. Inner class
@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //Loading layout FilesSetcontentview (R.layout.activity_main); //get the buttons in the layoutBTN =(Button) Findviewbyid (R.ID.BTN); //internal class implementation Click to listenBtn.setonclicklistener (NewMyclicklistener ()); } //define an inner class classMyclicklistenerImplementsonclicklistener{@Override Public voidOnClick (View arg0) {//TODO auto-generated Method StubToast.maketext (mainactivity. This, "internal class implementation Listener", Toast.length_short). Show (); } }
3. Implementing the interface
Defined activity implements the Onclicklistener interface and re-onclick () method
protected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); //Loading layout FilesSetcontentview (R.layout.activity_main); //get the buttons in the layoutBTN =(Button) Findviewbyid (R.ID.BTN); //increased listening, passing the This object, this represents the clicked controlBtn.setonclicklistener ( This); } @Override Public voidOnClick (view view) {//TODO auto-generated Method Stub Switch(View.getid ()) { CaseR.id.btn:toast.maketext (mainactivity. This, "Implementation of interface Implementation Monitoring", Toast.length_short). Show (); Break; } }
Three ways to implement Android for increased monitoring