将信息从 EventListener 传递回 Activity
我是 Android 新手,也是一般事件驱动代码的新手。我没有在 Activity 中嵌入大量匿名事件侦听器类来处理 onClick 事件等,而是定义了单独的类来保持代码整洁。然后我使用它们,例如像这样
myButton.setOnClickListener(new MyEventListener());
因此,当“myButton”被单击时,MyEventListener 的 onClick 方法会执行一些操作。
我想知道
a) 从事件侦听器访问我的 Activity 中的内容的最佳实践。例如更改标签的文本。 onClick 事件接受一个视图,但这是已单击按钮的视图,因此如果标签不是我的按钮的子级,我无法使用 findViewById 来获取它的句柄。我修改了构造函数以传递对标签的引用,以便事件有一个句柄,但不确定这是否是最优雅的方法。
b)传回信息,例如当我的事件触发时,我可能想禁用某些 EditText 字段。我认为执行此操作的正确方法可能是从我的事件侦听器调度另一个事件,活动侦听该事件,并且当它看到该事件时,禁用有问题的字段。 Android 中是这样实现的吗?
希望有人能帮忙,真的很感激。
谢谢
I'm new to Android, and event driven code in general. Rather than embed loads of anonymous event listener classes in my Activity to handle onClick events etc, I defined separate classes to keep the code clean. Then I use them e.g. like this
myButton.setOnClickListener(new MyEventListener());
So, when 'myButton' gets clicked, MyEventListener's onClick method does some stuff.
I wanted to know the best practice for
a) accessing things in my Activity from the event listener. For example to change the text of a label. The onClick event takes a View in, but this is the view for the button that's been clicked, so if the label is NOT a child of my button, I can't use findViewById to get a handle to it. I've modified the constructor to pass in a reference to the label, so that the event has a handle to it but not sure if this is the most elegant way of doing it.
b) Passing information back e.g. when my event fires, I might want to disable some EditText fields. I'm thinking the proper way to do this is probably to dispatch another event from my event listener, that the Activity listens for, and when it sees the event, disables the fields in question. Is that the way to do it in Android?
Hope someone can help, really appreciate it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用显式事件侦听器(无论是否匿名)的另一种方法是使用 xml 中的 onClick 属性来直接分派到方法,如以下示例所示:
布局 xml 文件:
现在简单地在您的活动:
自 Android 1.6 起可用,如 Android 1.6 中的 UI 框架发生变化。
An alternative to using explicit event listeners, anonymous or not, is to use the onClick attribute in xml to directly dispatch to a method as in the following example:
Layout xml file:
Now simple define a method on your activity:
This is available since Android 1.6 as described in UI framework changes in Android 1.6.