purewatashi21 purewatashi21 - 5 months ago 15
Android Question

Create boolean listener

In Android, how do I take an action whenever a variable changes?

So I want to implement a listener for an object I created. What I want it to do is execute a block of code when its value changes from false to true.

As I am following this thread, I can't understand where the person wants us to implement the last block of code containing the logic for the listener.

Could someone, hopefully, guide me in the right direction?

(This question is being asked here as I don't have enough rep. points)

Answer

That last bit of example code triggers the listener, so it basically needs to be run whenever the "event" occurs. In this case the "event" is whenever (wherever in the code) the value of the variable changes.

If you have a setter and that is the only place the value changes, that is where you'd put it. If you are changing the value in multiple places throughout your code, I would make a new private method (call it signalChanged), put your code there, and then call it immediately after the variable assignment in the cases you want the listener to fire.

Here's an example (some code borrowed from linked answer, haven't checked that it compiles).

public class MyObj
{        
    public MyObj(int value)
    {
        setValue(value);
    }

    private int myValue;
    public int getValue() { return myValue; }
    public void setValue( int value )
    {
        if (value != myValue)
        {
            myValue = value;
            signalChanged();
        }
    }

    public interface VariableChangeListener
    {
        public void onVariableChanged(Object... variableThatHasChanged);
    }

    private VariableChangeListener variableChangeListener;
    public void setVariableChangeListener(VariableChangeListener variableChangeListener)
    {
        this.variableChangeListener = variableChangeListener;
    }

    private void signalChanged()
    {
        if (variableChangeListener != null)
            variableChangeListener.onVariableChanged(myValue);
    }
}