我有它的作用就像一个按钮,自定义视图。我想改变,当用户preSS它,恢复的背景,原来的背景,当用户外移动手指或松开,我也想处理的onClick / onLongClick事件。问题是,onTouch要求我返回true ACTION_DOWN
,否则将不给我 ACTION_UP
事件。但是,如果我回到真正的的onClick
监听器将无法正常工作。
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.
我想我在onTouch返回false,并注册的onClick解决了这个问题 - 它在某种程度上工作,但有点儿反对文档。我刚刚收到的消息,从一个用户告诉我,他不能够在按钮上长按一下,所以我不知道什么是错在这里。
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.
目前的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?
在此先感谢
的onClick
&放大器; onLongClick
实际上是从调度 View.onTouchEvent
。
onClick
& onLongClick
is actually dispatched from View.onTouchEvent
.
如果您重写 View.onTouchEvent
或设置一些特定的 View.OnTouchListener
通过 setOnTouchListener
,
你必须关心的。
if you override View.onTouchEvent
or set some specific View.OnTouchListener
via setOnTouchListener
,
you must care for that.
让你的code应该是这样的:
so your code should be something like:
public boolean onTouch(View v, MotionEvent evt)
{
// to dispatch click / long click event,
// you must pass the event to it's default callback View.onTouchEvent
boolean defaultResult = v.onTouchEvent(evt);
switch (evt.getAction())
{
case MotionEvent.ACTION_DOWN:
{
setSelection(true); // just changing the background
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_OUTSIDE:
{
setSelection(false); // just changing the background
break;
}
default:
return defaultResult;
}
// if you reach here, you have consumed the event
return true;
}