Android 应用上的自定义事件监听器

时间:2023-03-20
本文介绍了Android 应用上的自定义事件监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我需要设置一个简单的事件侦听器来不时刷新 ListView.问题是我不知道如何生成事件.

I need to set up a simple event listener to refresh a ListView once in a while. The problem is I don't know how could I generate an event.

我知道对于按键或按钮按下等事件,我只需要实现 Handler.但在这种特定情况下,我实际上需要生成事件,每次我的应用程序的另一个正在运行的线程唤醒并刷新其来自 RSS 提要的新闻列表时,都会触发该事件.

I know that for events like key or button pressing I just need to implement the Handler. But in this specific case I actually need to generate the event, which will be fired every time another running thread of my app wakes up and refreshes its list of news from an RSS feed.

我什么都做了,却卡在了这里.我可以获得任何建议或链接以提供有关如何实施此功能的更多信息吗?

I've done everything, but got stuck in here. Can I get any suggestion or link with some more info on how to implement this?

推荐答案

  1. 定义回调接口

  1. Define a callback interface

        public interface NewsUpdateListener 
        {
            void onNewsUpdate(<News data to be passed>);
        }

  • 在获取 RSS 提要的后台线程上提供注册工具

  • Provide a registration facility on the background thread which gets the RSS feed

        class <Background processing class name> 
        {
        ....
            ArrayList<NewsUpdateListener> listeners = new ArrayList<NewsUpdateListener> ();
        .... 
            public void setOnNewsUpdateListener (NewsUpdateListener listener) 
            {
                // Store the listener object
                this.listeners.add(listener);
            }
        ....
        }
    

  • 有消息时触发回调

  • Fire the callback when news is available

    ....
    for (listener : listeners) 
    {
        listener.onNewsUpdate(<News data to be passed>);
    }
    ....
    

  • 在初始化期间在某处注册监听器

  • Register listener somewhere during initialization

    ....
        <class <Background processing class object>.registerListener
    (
        new OnNewsUpdateListener() {
            onNewsUpdate(<News Data>) {
                // process news data
                runOnUIThread(new Runnable() {
                    public void run() {
                        // refresh list view
                    }
                }
            }
    }
    ....
    

  • 这篇关于Android 应用上的自定义事件监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

    上一篇:处理菜单项点击事件 - Android 下一篇:onTouchEvent()中如何区分移动和点击?

    相关文章