简体   繁体   中英

Call a method on all classes that implements that method

I have an Activity and 10 fragments. I've created an interface and implement it on all Fragments. How can I call that method on all Fragments from the Activity?

  public interface OnConnectListener {
      void isDeviceConnected(boolean b);
  }

UPDATE:

Using your suggestions I did this:

public void isDeviceConnected(boolean b, List fragmentList) {
    for (OnConnectListener listener : getOnConnectListeners(fragmentList)) {
        listener.isDeviceConnected(b);
    }
}

public List<OnConnectListener> getOnConnectListeners(List fragmentList) {
    List<OnConnectListener> listeners = new ArrayList<>();
    for (Object o : fragmentList) {
        if (o instanceof OnConnectListener) {
            listeners.add((OnConnectListener) o);
        }
    }
    return listeners;
}

Now I just use:

isDeviceConnected(true, fragmentList);

Thank you so much.

Assuming your "Activity" class holds a reference of 10 "onConnectListener" instances, you can loop thru each and call isDeviceConnected like so:

private List<onConnectListener> onConnectListeners;
....
for(onConnectListener onConnectListener: onConnectListeners) {
    onConnectListener.isDeviceConnected(true); // or false
}

By the way: Java naming conventions state that class names start with capital letters, and iterfaces usually start with the letter "I" So its best if you name your interface IOnConnectListener

This is perfect case for Observer pattern

http://www.oodesign.com/observer-pattern.html

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