【问题标题】:Codename One event listening within a Container which contains more sub-ContainersCodename 在包含更多子容器的容器内侦听一个事件
【发布时间】:2017-02-28 07:31:54
【问题描述】:

我正在使用 Codename One 开发移动应用程序。

我有一个外部容器,我通过调用 addPointerReleasedListener 方法添加了一个 ActionListener

还有更多没有添加任何监听器的内部容器。

举例说明:

outer-Container (added `addPointerReleasedListener` to it)
 - An Image Container (NO listener added)
 - A Text Container (NO listener added)


--------------------------------------------------------------
| |            |                                             |
| |            |                                             |
| |   Image    |  Some Text here                             |
| |            |                                             |
| |            |                                             |
--------------------------------------------------------------
                                    ^        ^        ^
                                    works only if I click/press
                                    here

我注意到为了调用事件,我必须点击/按下一个没有占用任何内部容器的区域。也就是说,如果我单击/按下任何文本和图像区域(因为没有添加任何侦听器),它不起作用。我必须专门单击/按下外部容器的“空白”区域。显然,这没有任何意义,因为我想让整个容器在用户单击/按下容器中的任何位置时以相同的方式做出反应。

实现这一点的最佳方法/实践是什么? (我觉得向许多内部容器添加相同的侦听器有点多余。)

【问题讨论】:

  • 这个答案能解决你的问题吗?

标签: java codenameone


【解决方案1】:

您的方法在真实设备上无法正常工作。

创建一个按钮并将您的 actionListener 添加到其中,并将外部容器的 leadComponent 设置为该按钮。

Button btn = new Button("");
btn.addActionListener(e -> {
    //Your action here
});
outerContainer.setLeadComponent(btn);

您不必将该按钮添加到您的容器中,只需将其设置为leadComponent。

【讨论】:

  • 是的,这行得通。谢谢!但是,它现在在 (ActionEvent actionEvent) 的 getSource() 方法中发送该 Button。我必须通过使用接受外部容器作为参数的构造函数实例化侦听器来解决这个问题(这样我就可以响应正确的外部容器)。我不认为这会导致任何问题/内存泄漏,所以我认为这很好。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-06
相关资源
最近更新 更多