android on change class event

Solutions on MaxInterview for android on change class event by the best coders in the world

showing results for - "android on change class event"
Sara Sofía
18 Jan 2020
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):
2
3interface ConnectionBooleanChangedListener {
4    public void OnMyBooleanChanged();
5}
6
7public class Connect { 
8     private static boolean myBoolean;
9     private static List<ConnectionBooleanChangedListener> listeners = new ArrayList<ConnectionBooleanChangedListener>();
10
11     public static boolean getMyBoolean() { return myBoolean; }
12
13     public static void setMyBoolean(boolean value) {
14         myBoolean = value;
15
16         for (ConnectionBooleanChangedListener l : listeners) {
17             l.OnMyBooleanChanged();
18         }
19     }
20
21     public static void addMyBooleanListener(ConnectionBooleanChangedListener l) {
22         listeners.add(l);
23     }
24}
25
26//Then, wherever you want to listen to changes of the boolean, you can register a listener:
27
28Connect.addMyBooleanListener(new ConnectionBooleanChangedListener() {
29    @Override
30    public void OnMyBooleanChanged() {
31        // do something
32    }
33});
34
35//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.