Android:在自定义视图组中使用 onTouchEvent 和自定义视图
我有一个称为“Node”的自定义视图,它是称为“NodeGrid”的自定义 ViewGroup 的子级。 “NodeGrid”类更具体地扩展了RelativeLayout。
我的自定义视图类(“Node”)中有以下代码片段:
private boolean isBeingDragged = false;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
isBeingDragged = true;
}
else if (event.getAction() == MotionEvent.ACTION_UP)
{
isBeingDragged = false;
}
else if (event.getAction() == MotionEvent.ACTION_MOVE)
{
if (isBeingDragged)
{
float xPosition = event.getX();
float yPosition = event.getY();
//change the x and y position here
}
}
return false;
}
问题:
在此代码中设置断点后,似乎仅针对 MotionEvent 调用 onTouchEvent 。 ACTION_DOWN 情况,但不适用于其他两种情况(“动作向上”或“动作移动”)。有谁知道有什么可能导致这种情况发生吗?
另外(可能相关):
将视图添加到 ViewGroup 的方式重要吗?我注意到除了“addView”之外,还有其他方法可以将子项添加到 ViewGroup,例如“addFocusables”和“addTouchables”。现在我只是使用“addView”将子视图添加到 ViewGroup 中。
I have a custom view which I call "Node" that is a child of a custom ViewGroup called "NodeGrid". The "NodeGrid" class more specifically extends RelativeLayout.
I have the following code snippet in my custom view class ("Node"):
private boolean isBeingDragged = false;
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
isBeingDragged = true;
}
else if (event.getAction() == MotionEvent.ACTION_UP)
{
isBeingDragged = false;
}
else if (event.getAction() == MotionEvent.ACTION_MOVE)
{
if (isBeingDragged)
{
float xPosition = event.getX();
float yPosition = event.getY();
//change the x and y position here
}
}
return false;
}
The problem:
After having set breakpoints in this code, it seems like onTouchEvent is getting called only for the MotionEvent.ACTION_DOWN case, but not for either of the other two cases ("action up" or "action move"). Does anyone know of anything off hand that could be causing this to happen?
Also (could be related):
Does it matter how the view is added to the ViewGroup? I noticed that in addition to "addView" there are other methods for adding children to a ViewGroup such as "addFocusables" and "addTouchables". Right now I am simply adding the child view to the ViewGroup using "addView".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来自 SDK 文档:
当 ACTION_DOWN 事件被触发时,您需要返回 true 以表明您对与同一事件相关的后续调用感兴趣。
华泰
From the SDK Documentation:
You need to return true when the ACTION_DOWN event is triggered to indicate that you are interested in the subsequent calls relating to that same event.
HTH