添加/移除监听器,全局应用于所有活动。

huangapple go评论83阅读模式
英文:

Add/Remove Listener Globally to all the activity

问题

我的应用程序有大约50个活动,我想要在这些活动中注册/注销我的监听器。传统的方式是在每个活动中编写注册代码。是否有一种方法可以全局定义我的监听器?

英文:

My Application have around 50 activities to which I want to register/De-register my listener. Traditional way could be to register it by writing it in every activity. Is there any way to define my listener globally.

答案1

得分: 1

首先,我认为50个活动太多了,我认为你可能做错了一些事情。

其次,针对你的情况,你可以创建 BaseActivity 并在适当的生命周期事件中注册和注销你的监听器。

class BaseActivity: AppCompatActivity() {
    
    override fun onResume() {
        super.onResume()
        // 在这里注册你的监听器
    }

    override fun onStop() {
        super.onStop()
        // 在这里注销你的监听器
    }
}

然后,你将不再扩展 Activity,而是扩展 BaseActivity

英文:

Firstly, I think 50 activities are too much and I think you are doing something wrong.

Secondly, for your situation, you could make BaseActivity and register and unregister your listener in the appropriate lifecycle event.

class BaseActivity: AppCompatActivity() {

	
	override fun onResume() {
		super.onResume()
        //register your listener here
	}

	override fun onStop() {
		super.onStop()
        //unregister your listener here 
	}
}

and then rather than extending Activity, you will extend the BaseActivity

答案2

得分: 0

我建议您在一个中央注册器中注册您的活动,可以是一个同步的Set或List(我猜您需要为所有活动实现一个共同的接口,以便能够这样做)。然后您的监听器将能够处理此列表并在每个活动中注册。
或者监听器只会在这个中央注册器中注册。因此,注册器也将充当发布者的角色,并将订阅传递给所有已注册的活动。

英文:

I'd suggest you registering your activities at a central registrar, maybe a synchronized Set or List (I guess you need to implement a common interface for all your activities to be able to do so). Then your listener would be able to process this list and register at each and every activity.
Or the listener would just register at this central registrar. Thus, the registrar would be acting as a publisher as well, and passing subscriptions down to all registered activities.

huangapple
  • 本文由 发表于 2020年4月4日 20:18:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/61027970.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定