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

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

问题描述

在最近的Google IO期间,我们介绍了实施安静的客户端应用程序。不幸的是,它只是一个高层次的讨论,没有实现的源代码。



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





如何声明这些方法是?



我理解一个回调的想法 - 一段代码在某个事件发生后调用,但我不知道如何实现它。到目前为止,我实现回调的唯一方法是覆盖各种方法(例如onActivityResult)。



我觉得我对设计模式有一个基本的了解,但是

解决方案

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



正如随机示例:

  //回调接口
interface MyCallback {
void callbackCall();
}

//接受回调的类
class Worker {
MyCallback callback;

void onEvent(){
callback.callbackCall();
}
}

//选项1:

类回调实现MyCallback {
void callbackCall(){
/ / callback code here here
}
}

worker.callback = new Callback();

//选项2:

worker.callback = new MyCallback(){

void callbackCall(){
// callback代码到这里
}
};

我可能搞错了选项2的语法。

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.

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

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.

解决方案

In many cases, you have an interface and pass along an object that implements it. Dialogs for example have the 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.

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

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