简体   繁体   中英

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:

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). 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; most IDEs will realize you've added a new interface member and offer to add it to all of the implementing classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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