📜  android on change class 事件 - Java 代码示例

📅  最后修改于: 2022-03-11 14:52:33.214000             🧑  作者: Mango

代码示例1
//It's not possible directly. However, you can make your field private, add getters and setters, and create a method of adding listeners (this is called the Observer pattern):

interface ConnectionBooleanChangedListener {
    public void OnMyBooleanChanged();
}

public class Connect { 
     private static boolean myBoolean;
     private static List listeners = new ArrayList();

     public static boolean getMyBoolean() { return myBoolean; }

     public static void setMyBoolean(boolean value) {
         myBoolean = value;

         for (ConnectionBooleanChangedListener l : listeners) {
             l.OnMyBooleanChanged();
         }
     }

     public static void addMyBooleanListener(ConnectionBooleanChangedListener l) {
         listeners.add(l);
     }
}

//Then, wherever you want to listen to changes of the boolean, you can register a listener:

Connect.addMyBooleanListener(new ConnectionBooleanChangedListener() {
    @Override
    public void OnMyBooleanChanged() {
        // do something
    }
});

//Adding a method to remove listeners is left as an exercise. Obviously, for this to work, you need to make sure that myBoolean is only changed via setMyBoolean, even inside of Connect.