Android-three ways to implement listeners

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.