Android列表点击事件委托
我有一个使用数据库来显示一些数据的列表。用户可以对每个列表项执行多种操作,而不是实现用户使用长按来调出可能操作列表的上下文菜单,我想向每个项目添加按钮,以便用户只需点击按钮并执行操作。该列表可能很大,并且为每个列表项的每个按钮附加一个侦听器是多余的,所以我想做 Javascript 程序员对事件冒泡所做的事情,即将单个处理程序附加到像整个列表这样的顶级元素,并让点击事件会冒泡到它上面。我该怎么做呢?
I have a list that uses a database to display some data. There are several operations that the user can perform on each list item and instead of implementing a context menu where the user uses a long press to bring up a list of possible operations I would like to add buttons to each item so the user can just tap the button and perform the operation. The list can be potentially large and attaching a listener to each button for each list item is overkill so I would like to do what Javascript programmers do with event bubbling, i.e. attach a single handler to a top level element like the entire list and let the click events bubble up to it. How would I go about doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
View.OnClickListener.onClick() 不会冒泡,因此您提出的解决方案行不通。
OTOH, View.OnTouchListener.onTouch() 确实冒泡,所以这个可以使用,但它需要您手动处理 MotionEvent 的向下/向上来检测单击。
此外,如果您创建大量按钮,那么您确定添加 onCLick 处理程序会产生大量开销,特别是因为您可以为所有按钮注册相同的方法。
您尝试做的事情听起来像是不成熟的优化。在尝试处理之前,请确保确实存在影响用户的开销。
View.OnClickListener.onClick() does not bubble, so the solution you propose would not work.
OTOH, View.OnTouchListener.onTouch() does bubble so this could possibly be used, but it would require you to manually handle MotionEvent's down/up to detect a click.
Besides, if you create a lot of Buttons, than are you sure that adding onCLick handlers would be a lot of overhead, especially since you can register the same method for all of them.
What you are trying to do sounds like a premature optimization. Be sure there is real overhead affecting your users, before you try to deal with it.