Android callback mechanism
The callback function separates the caller from the callee, the caller does not care who the callee is, and the caller only needs to know the tuned function with the specific prototype and constraints.
1. Define a callback function;
2. The Party providing the function implementation submits the instantiation interface of the callback function to the caller at initialization time;
3. When a particular event or condition occurs, the caller uses the interface to invoke the callback function to process the event.
See a sentence to write a better description:A class called a method of Class C, and then the Class B in turn calls the Class A method d,d this method is called the callback method
First cite an Android source code in the classic example:
//接口类, B类实现接口,A类调用接口 publicinterface OnClickListener { void onClick(View v); }
//equivalent to Class A Public class mainactivity extends Activity implements Onclicklistener { PrivateButton button;@Override Public void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Button = (button) Findviewbyid (R.id.button1);//Class A instantiation interfaceButton.setonclicklistener ( This); }@Override Public void OnClick(View v) {//callback function}}
//equivalent to Class B Public class View implements drawable. Callback, keyevent. Callback, accessibilityeventsource { //Interface Instance protectedOnclicklistener Monclicklistener;//Interface instantiation Public void Setonclicklistener(Onclicklistener L) {if(!isclickable ()) {setclickable (true); } Monclicklistener = l; } Public Boolean PerformClick() {if(Monclicklistener! =NULL) {the implementation method of class-//b class invocationMonclicklistener.onclick ( This);return true; }return false; } }
The above example is very clear, here I use markdown to make a diagram to show:
Created with Rapha?l 2.1.2 Class A Class A Class B Class B Setcallback (This) implements Callback OnCallback () Interface callback{} Callback Callback OnCallback ()
Android principle-Callback mechanism