Simple Android applications (3)-add listeners and android listeners for your applications
When writing a program, you often encounter listeners, such as button click listeners and button listeners. The listener in android is the same as the callback function in java. It defines an interface in the underlying code to call high-level code. So what is a callback function? The Internet says"In WINDOWS, programmers want the system DLL to call a method they have compiled, so they use the CALLBACK function (CALLBACK) interface in the DLL to compile the program and call it. This is called CALLBACK. When calling an interface, you must strictly follow the defined parameters and methods and process the asynchronous function. Otherwise, the program will crash. This explanation seems to be quite difficult. Here is A simple example. programmer a writes A program (program a), which reserves the callback function interface and encapsulates the program. Programmer B wants a to call a method in program B, So he calls back the method in B through the interface in.According to my understanding, I dug A hole in program A and waited for you to fill in the content in program B. Do not fill? It's just getting stuck ~
I. Define callback Functions
Ii. Call the callback function
I am binding an interface to the Activity. The actual code is as follows:
public class MainActivity extends Activity implements CallerClass.CallBack{ private CallerClass caller; ...}
Inherits the CallBack interface in CallerClass. The Out method is as follows:
@ Override public void Out () {// TODO Auto-generated method stub System. out. println ("this is the output of Activity ");}
Finally, call the Out () method of CallerClass in onCreate:
caller = new CallerClass();caller.setCallBack(this);caller.Out();
Complete code:
Public class MainActivity extends Activity implements CallerClass. callBack {private CallerClass caller; @ Override protected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); caller = new CallerClass (); caller. setCallBack (this); caller. out () ;}@ Override public void Out () {// TODO Auto-generated method stub System. out. println ("this is the output on Activity ");}}
Iii. Results
Perfect ~
Interface is similar to a pointer in C ++. It is an address reference but does not generate memory. Therefore, we can grant methods to be executed to programs in advance. More than that, the interface plays a more powerful role in the design mode. The factory mode, builder mode, and observer mode all use interfaces.