on change listener android code example

Example: android on change class event

//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<ConnectionBooleanChangedListener> listeners = new ArrayList<ConnectionBooleanChangedListener>();

     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.

Tags:

Java Example