如何为变量android创建自定义侦听器? [英] How to create a custom listener for a variable android?

查看:86
本文介绍了如何为变量android创建自定义侦听器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为不断变化的变量创建自定义侦听器,并希望跟踪该变量,并在每次注册更改时更新我的​​显示(TextView).我已经从

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.

推荐答案

我可以想到很多方法,但是我认为最简单的方法就是为您不想监听"的变量创建一个包装器,实现一个getter和setter,当然也实现监听器接口. 让我们假设您想侦听"一个int变量:

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

然后您就使用它:

ObservableInteger obsInt = new ObservableInteger();

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

每次更改值(使用Set(...))时,如果不为null,则将调用侦听器-

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

这篇关于如何为变量android创建自定义侦听器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆