简体   繁体   English

如何在活动之间共享点击处理程序

[英]How to share on click handler between activities

场景,我有两个活动,活动 A 和活动 B,它们都从 Activity 扩展,我的 ActionBar 上也有一个基本菜单 xml,在handler()方法上定义了 onClick,我该如何使此方法可用于我的两个活动没有在两者中实施?,制作一个共同的活动 SuperClass 是唯一的方法吗?

The generic answer is that you could either make a common superclass, as you say, or you could create a helper class, where each Activity class that uses the method would have:通用的答案是,您可以创建一个通用的超类,如您所说,或者您可以创建一个辅助类,其中使用该方法的每个 Activity 类将具有:

public void onSomethingClick(View target){
    MyActionBarHelperMethods.onSomethingClick(View target, /* whatever other things from this class you need */);
}

This can get kind of verbose if you have a lot of things you want to handle this way, but it's less verbose than implementing the same method everywhere.如果您有很多事情想要以这种方式处理,这可能会变得有点冗长,但它比在任何地方实现相同的方法都简单。 It will also be painful to implement a new item in your action bar this way (since you'd have to add the method to every Activity you want to use it).以这种方式在您的操作栏中实现一个新项目也会很痛苦(因为您必须将该方法添加到您想要使用它的每个 Activity)。 However, once again, it's less painful than having to modify the method in every place if you want to change it.然而,再一次,如果你想改变它,它比在每个地方都修改方法更不痛苦。

One way to possibly mitigate the headache when you want to add a new method would be to make each Activity implement an interface that contains all of the action bar methods you want them to have;当您想要添加新方法时,可能减轻头痛的一种方法是让每个 Activity 实现一个接口,其中包含您希望它们拥有的所有操作栏方法; most IDEs will realize you've added a new interface member and offer to add it to all of the implementing classes.大多数 IDE 会意识到您添加了一个新的接口成员,并提议将其添加到所有实现类中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM