Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a custom listener for a variable android?

I'm trying to create a custom listener for a variable that changes continuously and want to keep a track of it and update my display (TextView) each time a change is registered. I've taken reference from In Android, how do I take an action whenever a variable changes? But, this runs only once. I want it to continuously track the changes and update display upon state change.

like image 500
Jay D Avatar asked May 20 '26 09:05

Jay D


1 Answers

I can think many ways of doing this, but I think the simplest one is just create a Wrapper of the variable you wan't to "listen" to, implemente a getter and a setter, and of course the listener interface. Lets supose you want to "listen" to an int variable:

public interface OnIntegerChangeListener
{
    public void onIntegerChanged(int newValue);
}

public class ObservableInteger
{
    private OnIntegerChangeListener listener;

    private int value;

    public void setOnIntegerChangeListener(OnIntegerChangeListener listener)
    {
        this.listener = listener;
    }

    public int get()
    {
        return value;
    }

    public void set(int value)
    {
        this.value = value;

        if(listener != null)
        {
            listener.onIntegerChanged(value)
        }
    }
}

Then you just use it:

ObservableInteger obsInt = new ObservableInteger();

obsInt.setOnIntegerChangeListener(new OnIntegerChangeListener()
{
    @Override
    public void onIntegerChanged(int newValue)
    {
        //Do something here
    }
});

Each time you change the value (with Set(...) ), the listener, if not null, will be called-

like image 118
JML Avatar answered May 22 '26 22:05

JML