Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement