我的班级中有一个变量,我希望当变量发生变化时,我会在另一个类中执行操作。 事实上我想要一个用于在android中更改变量的监听器(我的变量可能每分钟都在变化)
public class Connect {
public static boolean myBoolean;
//some actions do and myBoolean change
}
public class Selection extends Activity implements OnMenuItemClickListener{
//I want a thing like listener here ,when myboolean changed I do an action (myboolean may change every minute)
}
答案 0 :(得分:8)
直接不可能。但是,您可以将您的字段设为私有,添加getter和setter,并创建添加侦听器的方法(这称为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);
}
}
然后,无论您想要监听布尔值的更改,都可以注册一个监听器:
Connect.addMyBooleanListener(new ConnectionBooleanChangedListener() {
@Override
public void OnMyBooleanChanged() {
// do something
}
});
添加一个删除侦听器的方法留作练习。显然,为了实现这一点,您需要确保myBoolean
仅通过setMyBoolean
进行更改,即使在Connect
内也是如此。