gpt4 book ai didi

java - 在 Android 中,每当变量发生变化时,我如何采取行动?

转载 作者:IT老高 更新时间:2023-10-28 21:05:45 24 4
gpt4 key购买 nike

在 Android 应用程序中(或者更普遍的 Java,如果没有什么不同的话),当变量的值发生变化时调用方法的最佳方式是什么?

最佳答案

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

这通常通过以下步骤来完成:

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


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

您可以将任何您认为对监听器处理很重要的论点放在此处。通过抽象到接口(interface)中,您可以灵活地在变量发生变化的情况下实现必要的操作,而无需将其与发生事件的类紧密耦合。

  • 在事件发生的类中(同样在您的情况下,变量可能更改的类),添加一个方法来为事件注册一个监听器。如果你调用你的接口(interface) 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);
}

这也是编程中非常常见的做法,它基本上对事件或变量变化使用react。在 Javascript 中,您会看到这是 onclick() 的一部分,在 Android 中,您可以检查各种监听器的事件驱动模型,例如 OnClickListener设置在 Button点击事件。在您的情况下,您只需根据变量发生变化时的不同事件触发监听器

关于java - 在 Android 中,每当变量发生变化时,我如何采取行动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7157123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com