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.
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-
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With