How to Understand callback in java

Source: Internet
Author: User

How to Understand callback in java

Take the setOnClickListener callback of the Button in android as an example;

Button button = (Button) this. findViewById (R. id. button); button. setOnClickListener (new Button. onClickListener () {// callback function @ override publicvoid onClick (View v) {buttonTextView. setText ("the button has been clicked ");}});

How can we implement it;

First, define the OnClickListener interface.

Package com. listener;/*** click the listener interface * @ author CodingMyWorld **/publicinterface MyOnClickListener {publicvoid onClick ();}

Then define the Button class.

Package com. listener; publicclass MyButton {private MyOnClickListener listener;/*** set click listener * @ param listener click listener implementation class */publicvoid setOnClickListener (MyOnClickListener listener) {this. listener = listener;}/*** button is clicked */publicvoid doClick () {listener. onClick ();}}

Finally, write a test class.

Package com. listener; publicclass Client {publicstaticvoid main (String [] args) {MyButton button = new MyButton (); // register the listener button. setOnClickListener (new MyOnClickListener () {@ Override publicvoid onClick () {System. out. println ("the button has been clicked") ;}}); // simulate the user clicking the button. doClick ();}}


Okay, easy to understand. This is the callback.

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.