Detailed explanation and simple example of Android callback

Android callback

preface:

The classic callback in Android is the click event setting listening (generally through switch (v.getid()). Here is the most basic callback

View exposes an interface onclick

When we implement the specific method and write the processing, the current activity does not do any operation on this method. The enriched onclick method is processed by the view callback! One of the processes, such as

You can read view.java for details

2. What is a callback

Callback is actually a two-way calling mode, that is, when the interface is called, the caller will also call the other party's interface, which sounds awkward. Translation is to "implement the instance of the abstract class / interface, implement the abstract method provided by the parent class, and then return the method to the parent class for processing". Read the formula three times. Can you understand the connotation?

The main thing to make clear is that the implementation method is returned to the parent class that provides the interface for processing!

3. Why use callbacks

This reflects the java object-oriented "everything is an object". We need to abstract the characteristics of ordinary objects, and there are characteristics in the commonness. Each different characteristic needs to be handled by a specific situation. By exposing the interface method, we can reduce a lot of repetition and make the code more elegant. For example, view has the generality of being clicked, but each click will produce different events. Therefore, Android exposes that an interface has an onclick method. You can write whatever you need to handle. View will only call this method. You have handled different click events yourself.

4. How to write

A nice little chestnut

[define interface] define an interface in the class and an abstract method in the interface

[interface object] define a member variable of the interface in the class

[set object] define a public method in the class. You can set the object of this interface and call this method to assign a value to the interface object variable

[call method] call the method in the interface object

ok,

The complete code is as follows

Then we'll just use it

Thank you for reading, hope to help you, thank you for your support to this site!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>