如何在 Android 中定义回调? [英] How to Define Callbacks in Android?

查看:39
本文介绍了如何在 Android 中定义回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在最近的 Google IO 中,有一个关于实现 Restful 客户端应用程序的演示.不幸的是,这只是一个高层讨论,没有实现的源代码.

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.

在这个图中,在返回路径上有各种不同的对其他方法的回调.

In this diagram, on the return path there are various different callbacks to other methods.

如何声明这些方法是什么?

我理解回调的概念——一段在特定事件发生后被调用的代码,但我不知道如何实现它.到目前为止,我实现回调的唯一方法是覆盖各种方法(例如 onActivityResult).

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).

我觉得我对设计模式有一个基本的了解,但我一直对如何处理返回路径感到困惑.

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.

推荐答案

在许多情况下,您有一个接口并传递一个实现它的对象.例如,对话框具有 OnClickListener.

In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the OnClickListener.

举个随机例子:

// 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
   }
};

我可能搞砸了选项 2 中的语法.现在还早.

I probably messed up the syntax in option 2. It's early.

这篇关于如何在 Android 中定义回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆