Java for Android - how to create event listener for boolean variable

Go To StackoverFlow.com

1

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

2012-04-03 20:34
by Lee Hall


5

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.

2012-04-03 20:45
by Seva Alekseyev
Nice simple code snippet. It just missing the setter where the listener gets notified if one was set : - WarrenFaith 2012-04-03 20:53
The only thing missing from this answer is to define a setter method for mBoo that actually notifies the listener when the variable is set - Ted Hopp 2012-04-03 20:53
As the other two said, you missed setting the listener - Karl Morrison 2013-10-25 14:14


0

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.

2012-04-03 20:55
by user1288802
I don't think beans are currently supported on Android. Also, PropertyChangeListener is type-agnostic - Seva Alekseyev 2012-04-03 21:13