如何在Codename One中使属性更改侦听器

时间:2017-10-03 14:17:47

标签: codenameone

我正在尝试更新地图上的用户位置。所以我已经定义了我的LocationListener,如下所示:

public class UserLocationListener implements LocationListener {

  @Override
  public void locationUpdated(Location location) {
    User.getInstance().actualLocation.set(location);

  }

  @Override
  public void providerStateChanged(int newState) {

 }

}

actualLocation是在CN1 guide on Properties之后定义的属性。

在模拟器中,如果我使用位置模拟器移动用户位置,则会触发locationUpdated。

现在在我的MainForm类构造函数中添加:

User.getInstance().actualLocation.addChangeListener((p) -> {
        System.err.println("User location has changed");
        // Update user location on the map
}

虽然使用标记显示地图,但它永远不会被触发(参见myMap.addMarker(...))。

所以我的问题是:为什么这个改变听众没有被解雇,我应该把它放在哪里让所有工作?

任何帮助表示赞赏,

1 个答案:

答案 0 :(得分:2)

位置代码重用相同的位置对象实例,只是更改其中的值。如果新值set(T)为旧值,则属性中的!=方法仅触发更改事件:

public K set(T value) {
    if(this.value != value) { 
        this.value = value;
        firePropertyChanged();
    }
    if(parent == null) {
        // allows properties to work even if they aren't registered in the index
        return null;
    }
    return (K)parent.parent;
}

因此,作为一种解决方法,您可以使用以下内容:

public void locationUpdated(Location location) {
  Location l = new Location();
  l.setLatitude(location.getLatitude());
  ... // etc. sucks that we don't have new Location(location)
  User.getInstance().actualLocation.set(l);
}

我不确定我们是否需要它。