如何实现监听器 [英] How to implement a listener

查看:34
本文介绍了如何实现监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个设计问题.我需要实现一个监听器.我看到以下问题:如何在android中创建我们自己的监听器接口?

I have a design issue. I need to implement a listener. I saw the following SO question: How to create our own Listener interface in android?

但在答案中提供的链接中,作者创建了一个仅扩展系统定义的侦听器的侦听器.例如 onClick,你会做一些验证 &然后调用另一个名为whenValidatedListener"的方法

But in the link it provides in the answer, author creates a listener which just extends the system-defined listener. E.g onClick, you would do some validation & then call another method called "whenValidatedListener"

我需要定义未链接到现有事件侦听器的侦听器.基本上会在本机(C/C++)代码中进行一些处理&在 Android 代码中,我需要一个侦听器来响应来自它的某些消息.

I need to define listeners which are not linked to existing event listeners. Basically there would be some processing going on in native(C/C++) code & in the Android code I need a listener to respond to certain messages from it.

我想我可以使用处理程序来做到这一点.但是 AsyncTask 是推荐的多线程方法.

I think I could do this using handlers. But AsyncTask is the recommended approach for multithreading.

有没有办法使用 AsyncTask 实现用户定义的侦听器?

Is there a way to implement a user-defined-listener using AsyncTask?

推荐答案

AsyncTask 与实现监听器无关.

AsyncTask has nothing to do with implementing a listener.

这是一个听众:

public interface TheListener {
    public void somethingHappened();
}

随心所欲地称呼它.例如,这是一个执行类似 View 的类:

Call it however you want. For example, here's a class doing something like View:

public class Something {
    private TheListener mTheListener;

    public void setTheListener(TheListener listen) {
        mTheListener = listen;
    }

    private void reportSomethingChanged() {
        if (mTheListener != null) {
            mTheListener.somethingHappened();
        }
    }
}

您可以根据需要使其变得复杂.例如,您可以使用 ArrayList 代替单个侦听器指针,以允许注册多个侦听器.

You can make this as complicated as you want. For example, instead of a single listener pointer you could have an ArrayList to allow multiple listeners to be registered.

从本机代码调用它也与实现侦听器接口无关.您只需要了解 JNI 即可了解本机代码如何与 Java 语言代码进行交互.

Calling this from native code also has nothing to do with implementing a listener interface. You just need to learn about JNI to learn how native code can interact with Java language code.

这篇关于如何实现监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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