问题描述
我希望这将是简单的问题。我的主要活动,在这个活动我创建一些类的实例。如何发送某些事件形成一类主要的一个?如何设置某种监听器类之间发送通知。唯一的选择是什么,我知道/使用权,现在是保持引用父类和直接调用的子类的一些功能。
I hope this will be simple question.I have main activity, on this activity I create an instance of some class. How to send some event form one class to main one? How to setup some kind a listener to send notifications between classes. Only option what I know/use right now is to keep reference to parent class and call directly some function from child class.
我不知道是否有可能创造像在ActionScript中,在那里我可以打电话则dispatchEvent(新的事件(名字)),后来设置的addEventListener(姓名功能)??
I'm wonder if it possible to create something like is in ActionScript, where I can call to dispatchEvent(new Event("name")) and later setup addEventlistener("name" function) ??
推荐答案
如果我实现一些类意味着你已经宣告比嵌套的非静态类的活动类中的嵌套类将有一个引用父类对象
If "I implement some class" means that you have declared a nested class inside your Activity class than nested non-static class will have a reference to parent class object.
在一般情况下,你总是可以创建调度程序/侦听模式你的自我。创建监听器接口,并添加任何的addListener或使用setListener方法类,将调度事件。
In general, you can always create dispatcher/listener pattern your self. Create listener interface and add either addListener or setListener method to class that will dispatch event.
监听器的例子:
public interface IAsyncFetchListener extends EventListener {
void onComplete(String item);
void onError(Throwable error);
}
事件调度程序的示例:
Example of event dispatcher:
public class FileDownloader {
IAsyncFetchListener fetchListener = null;
...
private void doInBackground(URL url) {
...
if (this.fetchListener != null)
this.fetchListener.onComplete(result);
}
public void setListener(IAsyncFetchListener listener) {
this.fetchListener = listener
}
}
类与事件侦听器示例:
Example of class with event listener:
public class MyClass {
public void doSomething() {
FileDownloader downloader = new FileDownloader();
downloader.setListener(new IAsyncFetchListener() {
public void onComplete(String item) {
// do something with item
}
public void onError(Throwable error) {
// report error
}
});
downloader.start();
}
}
这篇关于Android的 - 事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!