Android onTouch 与 onClick 和 onLongClick
我有一个自定义视图,其作用类似于按钮。我想在用户按下它时更改背景,当用户将手指移到外面或释放它时将背景恢复为原始状态,我还想处理 onClick/onLongClick 事件。问题是 onTouch 要求我为 ACTION_DOWN
返回 true,否则它不会向我发送 ACTION_UP
事件。但如果我返回 true,onClick
侦听器将不起作用。
我想我通过在 onTouch 中返回 false 并注册 onClick 来解决它 - 它以某种方式起作用,但有点违反文档。我刚刚收到用户的消息,告诉我他无法长按按钮,所以我想知道这里出了什么问题。
当前代码的一部分:
public boolean onTouch(View v, MotionEvent evt)
{
switch (evt.getAction())
{
case MotionEvent.ACTION_DOWN:
{
setSelection(true); // it just change the background
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_OUTSIDE:
{
setSelection(false); // it just change the background
break;
}
}
return false;
}
public void onClick(View v)
{
// some other code here
}
public boolean onLongClick(View view)
{
// just showing a Toast here
return false;
}
// somewhere else in code
setOnTouchListener(this);
setOnClickListener(this);
setOnLongClickListener(this);
如何使它们正确地协同工作?
提前致谢
I've got a custom view which acts like a button. I want to change the background when user press it, revert the background to original when user moves the finger outside or release it and I also want to handle onClick/onLongClick events. The problem is that onTouch requires me to return true for ACTION_DOWN
or it won't send me the ACTION_UP
event. But if I return true the onClick
listener won't work.
I thought I solved it by returning false in onTouch and registering onClick - it somehow worked, but was kinda against the docs. I've just received a message from an user telling me that he's not able to long-click on the button, so I'm wondering what's wrong here.
Part of the current code:
public boolean onTouch(View v, MotionEvent evt)
{
switch (evt.getAction())
{
case MotionEvent.ACTION_DOWN:
{
setSelection(true); // it just change the background
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_OUTSIDE:
{
setSelection(false); // it just change the background
break;
}
}
return false;
}
public void onClick(View v)
{
// some other code here
}
public boolean onLongClick(View view)
{
// just showing a Toast here
return false;
}
// somewhere else in code
setOnTouchListener(this);
setOnClickListener(this);
setOnLongClickListener(this);
How do I make them work together correctly?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
onClick
&onLongClick
实际上是从View.onTouchEvent
调度的。如果您覆盖
View.onTouchEvent
或通过setOnTouchListener
设置某些特定的View.OnTouchListener
,你必须关心这一点。
所以你的代码应该是这样的:
onClick
&onLongClick
is actually dispatched fromView.onTouchEvent
.if you override
View.onTouchEvent
or set some specificView.OnTouchListener
viasetOnTouchListener
,you must care for that.
so your code should be something like: