Preface:

Just to give you one, my understanding of the callback mechanism: a callback is I don’t know exactly why you’re calling it, but I know what you’re probably doing. For example, click, the source code writer does not know whether to click the button after login, or pop up a dialog box, but the source code writer knows that the button loaded and the human hand touch and lift the action is click.

Instead of looking at android click events, let’s do a callback ourselves.

Chapter one: The headmaster goes to a meeting

Imagine a scenario (solemnly, this example is not for anyone, just for example, if it causes discomfort, please turn it off)

Everyone has been to school, and the boss of the school is assumed to be the headmaster, whose job is to manage students to study hard and grow up happily. But one principal could not manage thousands of students, so the work had to be divided between the head teacher and the director of the guidance office.

There are always some naughty students in our school. The headmaster has to take care of them. There are two kinds of naughty students in our school: talk and fuck. All right, the principal defined the speaking and typing modules before he left.

package TestCallBack; * @author Robin ** / public class XiaoZhang {// DoJob mDoJob; Public interface DoJob {void talk(String teacherName); // say void fuck(String teacherName, String tool); Public void setmDoJobCallBack(String teacherName, String tool, DoJob DoJob) {if (DoJob! = null) { doJob.talk(teacherName); // Work is --> say doJob. Fuck (teacherName, tool); // The job is --> hit}}}Copy the code

Chapter two: the principal left, the students exploded, the teacher fire

After the principal left, the students do whatever they want, the teacher in charge saw something bad, immediately began to work.

package TestCallBack; import TestCallBack.XiaoZhang.DoJob; /** * @author Robin ** / public class ClassTeacher implements DoJob {public void talk(String teacherName) {// System.out.println(" teacherName "+ "teacherName "); } public void fuck(String teacherName, String tool) {system.out.println (" teacherName "+ "teacherName "+" teacherName "+ "tool "); }}Copy the code

(For the record, we do not advocate hitting students)

Headteacher: Hello, headmaster? I want to tube the student principal: good then the principal new an object, and pass in the head teacher, let the head teacher tube the student

XiaoZhang xz = new XiaoZhang(); // Create a principal xz.setmdoJobCallback (" Li Erdog ", "Teaching whip ", new ClassTeacher());Copy the code

Log print :(what happened with eclipse? Who is not from EC…)

Teaching director to manage students in the same way:

package TestCallBack; import TestCallBack.XiaoZhang.DoJob; /** * @author Robin ** / public class implements DoJob {public void talk(String teacherName) Println (" teacherName "+" teacherName "); // teacherName (" teacherName "+" teacherName "); } public void fuck(String teacherName, String tool) {system.out. println(" teacherName "+" teacherName "+" teacherName "+" teacherName "+" teacherName "+" teacherName "); }}Copy the code

Create the object and execute

XiaoZhang xz = new XiaoZhang(); // Create a principal xz.setmdoJobCallback (" Monger · Kahn ", "Axe ", new JaoDaoChuTeacher());Copy the code

Log is printed as follows:

Notice here, if I want to rewrite the dean’s talk fuck method, how do I write it?

Xz.setmdojobcallback (" mongo Kahn ", "Axe ", new JaoDaoChuTeacher(){ @Override public void talk(String teacherName) { // super.talk(teacherName); System.out.println(teacherName); } @override public void fuck(String teacherName, String tool) {super.fuck(teacherName, tool); Println (" please go to tea and eat melon seeds "); // Then drink tea and eat melon seeds}});Copy the code

Notice super, which calls the method of the parent class.

Print the following:

Chapter three: The headmaster returns

The principal found that the effect was not good, the students were still very naughty, so the principal hired someone else, not the director of the guidance office, nor the head teacher, but a new role. His name was Robin, and he was good at using a whip. The first step is to have the consent of a principal, so you need to create a principal object

XiaoZhang xz = new XiaoZhang(); // Create a principal xz.setmdoJobCallback (" Robin ", "Whip ", New DoJob() {DoJob public void Talk (String teacherName) {// TODO auto-generated method stub System.out.println(teacherName + "Talking to me "); } public void fuck(String teacherName, String tool) {// TODO auto-generated method stub system.out.println (" teacherName, String tool) I was "+ teacherName +" with "+ tool + "); }});Copy the code

log:

The end.

And finally, let’s look at what I suggested at the beginning

A callback is I don’t know exactly why you’re calling it, but I know what you’re probably doing.

The principal makes a seat this manages the student’s job, the principal does not know who is specific to do, how to do, but the principal knows tube the student has to say and dozen two kinds of way. This is called the callback function

You thought it was over? Look at the scroll bar on the right, kid. This is the beginning. This is the beginning. (Java programmers should read the following.) So the question is, is there a J8 for callbacks?

At the earliest, we all know that I request network data, generally there are two callback methods onSuccess onFailed yes, I grew up with xUtils. After searching online, the network callback pseudocode used here looks something like this:

public static void sendHttpRequest(final String address, final HttpCallbackListener listener) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection connection = null; try { ... HttpUrlConnection while ((line = read.readline ())! Response.append (line); } if (listener ! = null) {// Call onSuccess() with listener.onSuccess(response.toString()); } } catch (Exception e) { if (listener ! = null) {// Callback onFailed() with an error listener.onfailed (e); } } finally { if (connection ! = null) { connection.disconnect(); } } } }).start(); }Copy the code

I didn’t get it before, but NOW I feel like I do.

Did you think it was over? Android uses many callback mechanisms, such as button click events and thread run() methods. This is a good article, and I quote, the author don’t hit me

1. Add click events to RecyclerView items

Public class ClickAdapter extends RecyClerView. Adapter{private OnClickItemListener mOnClickItemListener; Public void setOnClickItemListener(OnClickItemListener OnClickItemListener) {mOnClickItemListener = onClickItemListener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { . . . } @Override public void onBindViewHolder(ViewHolder holder, int position) { . . . } @Override public int getItemCount() { . . . } public class ViewHolder extends RecyclerView.ViewHolder{ // ... Public ViewHolder(View itemView) {....} Call */ public void bindHolder(final String Text) {mTextView.settext (text); if (null ! = mOnClickItemListener) { itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) {/ / in the click event callback mOnClickItemListener onClick (text); }}); Interface OnClickItemListener{void onClick(String text); }}Copy the code

So, interface callbacks can be summarized in the following four steps:

  • Creating an Internal Interface
  • Defining interface instances
  • Sets setter methods for the interface instance
  • Callbacks are made in click events

2. Load the network picture with the sub-thread and display it in the main thread

public class ImageUtil { public static void loadeIamge(final String url, final LoadeImageListener listener) { new Thread(new Runnable() { @Override public void run() { InputStream is = null; BufferedInputStream bis = null; try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setConnectTimeout(5000); connection.connect(); is = connection.getInputStream(); bis = new BufferedInputStream(is); // Get the bitmap and call onLoadeImageListener. listener.onLoadeImageListener(BitmapFactory.decodeStream(bis)); } catch (Exception e) { e.printStackTrace(); }finally { CloseUtil.closeQuietly(is); CloseUtil.closeQuietly(bis); } } }).start(); } public interface LoadeImageListener { void onLoadeImageListener(Bitmap bitmap); }}Copy the code

The above code is a utility class for loading network images. You can see that there is no interface instance defined, nor setter methods for interface instances defined. Instead, you operate directly with the interface instance from the caller.

Let’s look at the caller’s implementation:

final ImageView imageView = (ImageView) findViewById(R.id.image_view); ImageUtil.loadeIamge(IMG_URL, new ImageUtil.LoadeImageListener() { @Override public void onLoadeImageListener(Bitmap bitmap) { imageView.setImageBitmap(bitmap); }});Copy the code

To the end. . . . . . . . . . . . This is really gone.

All you have to do is like it. Thank you. I’m gonna call Dota.