First: In a class, define a class interface, and then give the definition of the class (the simplest and most intuitive)
Public classTestextendsactivity{Button btn; Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R,layout.main); ///Add Listener to buttonMyonclicklistener listener=NewMyonclicklistener (); Btn.setonclicklistener (listener); } ///give the definition of the listener class classMyonclicklistenerImplementsonclicklistener{@Override Public voidOnClick (View arg0) {toast.maketest......show (); } }}
The second kind: using anonymous inner classes (the one you see most often, is actually writing the first type together)
Public class extends Activity {Button btn; Public void onCreate (Bundle savedinstancestate) { super. OnCreate (savedinstancestate); Setcontentview (r. layout.main); // anonymous inner class notation Btn.setonclicklistener (new Onclicklistener () { @Override public void onclic (View v) { Toast. maketest....show (); }} );}}
Third: Use more simplification to implement the listener interface directly on the class
Public classTestextendsActivityImplementsOnclicklistener{button btn; Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (r. Layout.main); Btn.setonclicklistener ( This);} //////The direct override of the OnClick method can@Override Public voidOnClick (View v) {Toast. Maketext (...). Show (); }}
Android-three ways to implement listeners