android java 调用 另一个java 的变量的值,java – 在Android中,如果变量发生变化,该怎么做?...

您真正想要做的是设置事件驱动的模型,以在事件发生时触发监听器(在您的情况下,说变量值已更改)。这非常普遍,不仅适用于Java,还适用于其他编程语言,尤其是在UI编程的上下文中(尽管不一定仅仅是为此)

通常这样做是通过以下步骤完成的:

>决定在触发事件的情况下监听器应实现的接口。对于您的情况,您可以将其称为VariableChangeListener,并将接口定义为:

public interface VariableChangeListener {

public void onVariableChanged(Object... variableThatHasChanged);

}

您可以提出任何您认为重要的参数,以供听众处理。通过抽象到接口中,您可以灵活地实现必要的操作,在变量已更改的情况下,与事件发生的类紧密耦合。

>在事件发生的类中(再次在你的情况下,变量可以改变的类),添加一个方法来为事件注册一个监听器。如果你调用你的接口VariableChangeListener,那么你将有一个方法,如

// while I only provide an example with one listener in this method, in many cases

// you could have a List of Listeners which get triggered in order as the event

// occurres

public void setVariableChangeListener(VariableChangeListener variableChangeListener) {

this.variableChangeListener = variableChangeListener;

}

默认情况下没有人听事件

>在发生事件(变量已更改)的情况下,您将触发监听器,代码将类似于此

if( variableValue != previousValue && this.variableChangeListener != null) {

// call the listener here, note that we don't want to a strong coupling

// between the listener and where the event is occurring. With this pattern

// the code has the flexibility of assigning the listener

this.variableChangeListener.onVariableChanged(variableValue);

}

再次,这是编程中非常常见的做法,以对事件或变量进行基本的反应。在Javascript中,您看到这是onclick()的一部分,在Android中,您可以检查各种监听器的事件驱动模型,例如Button onclick事件上设置的OnClickListener。在您的情况下,您将只是根据不同的事件触发监听器,这是当变量发生变化时

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值