Android interface callback mechanism
During development, interface callback is frequently used. The interface callback means that execution is triggered at a certain time rather than immediately after registration. For example, if A does not have A problem, he will ask B. B cannot solve it for the moment. B said, I will tell you after I (B) have solved it. () at this time, A can continue to do other things first. Then, only after B solves the problem will A be able to solve the problem. In code, for example, the most commonly used method is: An Activity provides an interface callback Method for a button. Only when the user clicks this button and tells the button to be clicked will the interface callback method be executed.
Button btn = new Button(this); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { } });
The following uses a Demo to understand the interface callback: the main thread starts an asynchronous task. When the asynchronous task receives data, the data is displayed 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 and use the interface as the constructor parameter. In the doInBackground () method, determine if data exists, interface callback
package com.xqx.InterfaceDemo;import android.content.Context;import android.os.AsyncTask;public class MyTask extends AsyncTask<String,Void,String>{ private ChangeTitle changeTitle; public MyTask(ChangeTitle changeTitle) { this.changeTitle = changeTitle; } @Override protected String doInBackground(String... strings) { if (strings[0]!=null){ changeTitle.onChangeTitle(strings[0]); } return null; }}
3. The main Activity transmits this to the asynchronous task parameter, that is, the interface callback method is executed in this class, so you need to implement the ChangeTitle interface and rewrite the onChangeTitle method in the interface.
Package com. xqx. interfaceDemo; import android. app. activity; import android. OS. bundle; import android. view. view; import android. widget. textView; public class MainActivity extends Activity implements ChangeTitle {private TextView textView; @ Override public void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. main); textView = (TextView) findViewById (R. id. textView); new MyTask(this).exe cute ("I am the title");} // rewrite the interface method and perform the corresponding operation @ Override public void onChangeTitle (String title) {textView. setText (title );}}