I am creating an android application using Java. I have a boolean variable called "movement". I want to create an event that triggers when the value of "movement" changes. Any pointers in the right direction would be great. Thank you
A variable is not alone, I presume. It resides as a member in a class - right? So the listener interface would be nested in that class, and the class would have a member variable for a listener, and a setBooChangeListener method. And on every change to the variable (it's not public, I hope) you'd call the listener, if any. That's pretty much it.
class C
{
private boolean mBoo; //that's our variable
public interface BooChangeListener
{
public void OnBooChange(boolean Boo);
}
private BooChangeListener mOnChange = null;
public void setOnBooChangeListener(BooChangeListener bcl)
{
mOnChange = bcl;
}
}
There's no way to have the system (Java) watch the variable and automatically fire a listener whenever it's changed. There's no magic.
mBoo
that actually notifies the listener when the variable is set - Ted Hopp 2012-04-03 20:53
I wish I could add this as a comment...I agree with the most part with Seva above, however, consider making the class a bean and implementing the PropertyChangeListener interface:
http://docs.oracle.com/javase/1.4.2/docs/api/java/beans/PropertyChangeListener.html
bean properties can indeed be bound and watched in this manner. In javafx 2.0 Oracle added some really advanced mechanisms for doing this between properties and UI elements and I really hope this can be branched into the core API and somehow become available for Android devs. If JavaFX 2.0 is too late to the game we may get some of the more modern paradigm shifts in the core at least so situations like this can be implemented in a simple and rational way.