Android interface callback and android callback
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:
A does not have A problem. He will ask B. B cannot solve it for the time being. B said, I will tell you after I solve it (B) 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.
For example, the most common code:
In an Activity, a button is provided with an interface callback method. Only when the user clicks this button and notifies the button that it has been clicked can the callback method of the button interface 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 and 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, the interface calls back if data exists.
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(thisw..exe cute ("I am the title ");}
// Rewrite the interface method and perform the corresponding operation @ Override public void onChangeTitle (String title) {textView. setText (title );}}