In development, interface callbacks are often used by us.
The meaning of an interface callback is that it does not execute immediately after registration and triggers execution at some time.
As an example:
A There is a problem not, he went to ask B,b temporarily resolved not to come out, B said, wait for me (B) to solve and then tell you (a) at this point A can continue to do other things first.
Then only when B solves the problem and tells a problem solved, a can solve the problem.
In the code, such as the most commonly used:
An activity to give the button an interface callback method, only the user clicked the button, tell the button is clicked, will execute the button interface callback method
New Button (this); Btn.setonclicklistener (new View.onclicklistener () { @Override public void OnClick (view view) { } });
Then the following is a demo to understand the interface callback:
The main thread opens an asynchronous task, and when the asynchronous task receives the data, it displays the data in TextView.
1, first we need to define an interface, define a method, the parameter is a string:
Package Com.xqx.InterfaceDemo; Public Interface Changetitle { void Onchangetitle (String title); }
2, write an asynchronous task, the interface as a constructor method parameters, in the Doinbackground () method to determine if there is data, the interface callback
Package com.xqx.interfacedemo;import Android.content.context;import android.os.AsyncTask; Public classMyTask extends Asynctask<string,void,string>{ PrivateChangetitle Changetitle; PublicMyTask (Changetitle changetitle) { This. Changetitle =Changetitle; } @Overrideprotectedstring Doinbackground (String ... strings) {if(strings[0]!=NULL) {changetitle.onchangetitle (strings[0]); } return NULL; }}
3, the main activity, to the asynchronous task parameter pass this, that is, the interface callback method executes in this class, then need to implement Changetitle interface, rewrite interface Onchangetitle method
Package Com.xqx.interfacedemo;import android.app.activity;import android.os.bundle;import Android.view.View; Import Android.widget.TextView; Public classMainactivity extends Activity implements Changetitle {PrivateTextView TextView; @Override Public voidonCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.main); TextView=(TextView) Findviewbyid (R.id.textview); NewMyTask ( This). Execute ("I am the title"); }
Override the interface method to perform the appropriate action @Override Public voidOnchangetitle (String title) {Textview.settext (title); }}
Android Interface callback mechanism