如何在 Android 中定义回调?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3398363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Define Callbacks in Android?
提问by user409841
During the most recent Google IO, there was a presentation about implementing restful client applications. Unfortunately, it was only a high level discussion with no source code of the implementation.
在最近的 Google IO 中,有一个关于实现 Restful 客户端应用程序的演示。不幸的是,这只是一个高级别的讨论,没有实现的源代码。
In this diagram, on the return path there are various different callbacks to other methods.
在这个图中,在返回路径上有对其他方法的各种不同的回调。
How do I declare what these methods are?
我如何声明这些方法是什么?
I understand the idea of a callback - a piece of code that gets called after a certain event has happened, but I don't know how to implement it. The only way I've implemented callbacks so far have been overriding various methods (onActivityResult for example).
我理解回调的想法 - 在某个事件发生后调用的一段代码,但我不知道如何实现它。到目前为止,我实现回调的唯一方法是覆盖各种方法(例如 onActivityResult)。
I feel like I have a basic understanding of the design pattern, but I keep on getting tripped up on how to handle the return path.
我觉得我对设计模式有一个基本的了解,但我一直被如何处理返回路径绊倒。
回答by EboMike
In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.
在许多情况下,您有一个接口并传递一个实现它的对象。例如,对话框具有 OnClickListener。
Just as a random example:
就像一个随机的例子:
// The callback interface
interface MyCallback {
void callbackCall();
}
// The class that takes the callback
class Worker {
MyCallback callback;
void onEvent() {
callback.callbackCall();
}
}
// Option 1:
class Callback implements MyCallback {
void callbackCall() {
// callback code goes here
}
}
worker.callback = new Callback();
// Option 2:
worker.callback = new MyCallback() {
void callbackCall() {
// callback code goes here
}
};
I probably messed up the syntax in option 2. It's early.
我可能搞砸了选项 2 中的语法。现在还早。
回答by HGPB
When something happens in my view I fire off an event that my activity is listening for:
当我认为发生某些事情时,我会触发一个我的活动正在侦听的事件:
// DECLARED IN (CUSTOM) VIEW
// 在(自定义)视图中声明
private OnScoreSavedListener onScoreSavedListener;
public interface OnScoreSavedListener {
public void onScoreSaved();
}
// ALLOWS YOU TO SET LISTENER && INVOKE THE OVERIDING METHOD
// FROM WITHIN ACTIVITY
public void setOnScoreSavedListener(OnScoreSavedListener listener) {
onScoreSavedListener = listener;
}
// DECLARED IN ACTIVITY
// 在活动中声明
MyCustomView slider = (MyCustomView) view.findViewById(R.id.slider)
slider.setOnScoreSavedListener(new OnScoreSavedListener() {
@Override
public void onScoreSaved() {
Log.v("","EVENT FIRED");
}
});
If you want to know more about communication (callbacks) between fragments see here: http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
如果您想了解有关片段之间的通信(回调)的更多信息,请参见此处:http: //developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
回答by dragon
No need to define a new interface when you can use an existing one: android.os.Handler.Callback
. Pass an object of type Callback, and invoke callback's handleMessage(Message msg)
.
当您可以使用现有接口时,无需定义新接口:android.os.Handler.Callback
. 传递一个回调类型的对象,并调用回调的handleMessage(Message msg)
.
回答by Amol Patil
Example to implement callback method using interface.
使用接口实现回调方法的示例。
Define the interface, NewInterface.java.
定义接口NewInterface.java。
package javaapplication1;
包 javaapplication1;
public interface NewInterface {
void callback();
}
Create a new class, NewClass.java. It will call the callback method in main class.
创建一个新类NewClass.java。它将调用主类中的回调方法。
package javaapplication1;
public class NewClass {
private NewInterface mainClass;
public NewClass(NewInterface mClass){
mainClass = mClass;
}
public void calledFromMain(){
//Do somthing...
//call back main
mainClass.callback();
}
}
The main class, JavaApplication1.java, to implement the interface NewInterface - callback() method. It will create and call NewClass object. Then, the NewClass object will callback it's callback() method in turn.
主类 JavaApplication1.java,用于实现接口 NewInterface - callback() 方法。它将创建并调用 NewClass 对象。然后,NewClass 对象将依次回调它的 callback() 方法。
package javaapplication1;
public class JavaApplication1 implements NewInterface{
NewClass newClass;
public static void main(String[] args) {
System.out.println("test...");
JavaApplication1 myApplication = new JavaApplication1();
myApplication.doSomething();
}
private void doSomething(){
newClass = new NewClass(this);
newClass.calledFromMain();
}
@Override
public void callback() {
System.out.println("callback");
}
}
回答by MrGnu
to clarify a bit on dragon's answer (since it took me a while to figure out what to do with Handler.Callback
):
澄清一下 Dragon 的回答(因为我花了一段时间才弄清楚该怎么做Handler.Callback
):
Handler
can be used to execute callbacks in the current or another thread, by passing it Message
s. the Message
holds data to be used from the callback. a Handler.Callback
can be passed to the constructor of Handler
in order to avoid extending Handler directly. thus, to execute some code via callback from the current thread:
Handler
可用于在当前或另一个线程中执行回调,通过传递它Message
s。Message
要从回调中使用的保留数据。aHandler.Callback
可以传递给的构造函数,Handler
以避免直接扩展 Handler。因此,要通过当前线程的回调执行一些代码:
Message message = new Message();
<set data to be passed to callback - eg message.obj, message.arg1 etc - here>
Callback callback = new Callback() {
public boolean handleMessage(Message msg) {
<code to be executed during callback>
}
};
Handler handler = new Handler(callback);
handler.sendMessage(message);
EDIT: just realized there's a better way to get the same result (minus control of exactly when to execute the callback):
编辑:刚刚意识到有一种更好的方法可以获得相同的结果(减去对执行回调的确切时间的控制):
post(new Runnable() {
@Override
public void run() {
<code to be executed during callback>
}
});
回答by Rohit Mandiwal
You can also use LocalBroadcast
for this purpose. Here is a quick quide
您也可以LocalBroadcast
用于此目的。这是一个快速指南
Create a broadcast receiver:
创建广播接收器:
LocalBroadcastManager.getInstance(this).registerReceiver(
mMessageReceiver, new IntentFilter("speedExceeded"));
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Double currentSpeed = intent.getDoubleExtra("currentSpeed", 20);
Double currentLatitude = intent.getDoubleExtra("latitude", 0);
Double currentLongitude = intent.getDoubleExtra("longitude", 0);
// ... react to local broadcast message
}
This is how you can trigger it
这是你可以触发它的方式
Intent intent = new Intent("speedExceeded");
intent.putExtra("currentSpeed", currentSpeed);
intent.putExtra("latitude", latitude);
intent.putExtra("longitude", longitude);
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
unRegister receiver in onPause:
在 onPause 中取消注册接收器:
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
}