Android:带有 X & 的自定义视图 onClickEventY 地点 [英] Android: custom view onClickEvent with X & Y locations

查看:24
本文介绍了Android:带有 X & 的自定义视图 onClickEventY 地点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义视图,我想获取用户点击的 X 和 Y 坐标.我发现我只能从 onTouchEvent 获取坐标,如果我有 onTouchEvent,则 onClickEvent 不会触发.不幸的是,当用户拖动屏幕和点击时 onTouchEvent 会触发.

I've got a custom view and I want to get the X and Y coordinates of a user click. I've found that I can only get the coordinates from the onTouchEvent and an onClickEvent won't fire if I have an onTouchEvent. Unfortunately the onTouchEventfires when the user drags the screen as well as clicking.

我已尝试区分两者,但在拖动时仍会触发代码:

I've tried to differentiate between the two, but I still get the code firing when I'm dragging:

 public boolean onTouchEvent(MotionEvent event) {
  int action = event.getAction();
  if (action == MotionEvent.ACTION_DOWN) {
                //fires on drag and click

我看过这个,但正如我上面提到的,我不不认为那里的解决方案会起作用,因为我无法让 onClick 和 onTouch 事件同时工作.也许我在这方面做错了什么,有没有一种正常的方法来处理在自定义事件上捕获用户输入的问题?我应该能够同时使用 onClick 和 onTouch 事件吗?

I've had a look at this but as I mentioned above I don't think the solution there will work as I can't get the onClick and the onTouch events working at the same time. Maybe I'm doing something wrong in this respect, is there a normal way of dealing with capturing user input on custom events? Should I be able to use the onClick and onTouch events at the same time?

谢谢,马丁

推荐答案

现在不知道onTouchEvent短路onClick,不知道有没有必要设置android:clickable 为真(或 setClickable(true)).但是,如果你不能让它干净地工作,你可以在 onTouchEvent 中使用一个布尔值来模拟点击检测,如果所有其他方法都失败了.在 ACTION_DOWN 中,将其设置为 true(isClicking 或类似的东西),在 ACTION_MOVE 中将其设置为 false(因为用户正在拖动因此未单击),然后在 ACTION_UP 中您可以对其进行测试.如果为真,则表示用户已按下但未拖动.这很hacky,但如果您无法使用onClick 工作,那基本上是一样的.

Now, I don't know about onTouchEvent short circuiting onClick, and I don't know if maybe you need to set android:clickable to true (or setClickable(true)). But, if you can't make it work cleanly, you can use a boolean in the onTouchEvent to mimic click detection if all else fails. in ACTION_DOWN, set it to true (isClicking or something like that), in ACTION_MOVE set it to false (because the user is dragging therefore not clicking) and then in ACTION_UP you can test for it. If it's true, this means the user has pressed down but not dragged. It's hacky, but if you can't get onClick to work it's basically the same thing.

这篇关于Android:带有 X & 的自定义视图 onClickEventY 地点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆