Lee Hall
Lee Hall

Reputation: 15

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

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

Upvotes: 1

Views: 7578

Answers (2)

Seva Alekseyev
Seva Alekseyev

Reputation: 61351

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;
    }

    public void setBoo(boolean b)
    {
         mBoo = b;
         if(mOnChange != null)
             mOnChange.onBooChange(b);
    }
}

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.

Upvotes: 6

user1288802
user1288802

Reputation: 83

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.

Upvotes: 0

Related Questions