Android onTouch带有onClick和onLongClick
我有一个像按钮一样的自定义视图。我想在用户按下它时更改背景,在用户将手指移出或释放它时将背景还原为原始背景,我还想处理onClick/onLongClick事件。问题在于,onTouch要求我为Android onTouch带有onClick和onLongClick,android,click,touch,Android,Click,Touch,我有一个像按钮一样的自定义视图。我想在用户按下它时更改背景,在用户将手指移出或释放它时将背景还原为原始背景,我还想处理onClick/onLongClick事件。问题在于,onTouch要求我为操作_DOWN返回true,否则它不会向我发送操作_UP事件。但是如果我返回true,onClick侦听器将无法工作 我想我通过在onTouch中返回false并注册onClick解决了这个问题——它不知怎么地起了作用,但有点违背了文档。我刚刚收到一个用户的消息,告诉我他不能长时间点击按钮,所以我想知道这
操作_DOWN
返回true,否则它不会向我发送操作_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);
如何使它们正确地协同工作
提前感谢
onClick
&onLongClick
实际上是从视图中发送的
如果通过setOnTouchListener
覆盖View.onTouchEvent
或设置某些特定的View.OnTouchListener
,
你一定会在意的
因此,您的代码应该类似于:
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;
}
公共布尔onTouch(视图v、运动事件evt)
{
//要分派单击/长单击事件,
//您必须将事件传递给它的默认回调视图。onTouchEvent
布尔值defaultResult=v.onTouchEvent(evt);
开关(evt.getAction())
{
case MotionEvent.ACTION\u DOWN:
{
setSelection(true);//只是更改背景
打破
}
case MotionEvent.ACTION\u取消:
case MotionEvent.ACTION\u UP:
case MotionEvent.ACTION_外部:
{
setSelection(false);//只是更改背景
打破
}
违约:
返回默认结果;
}
//如果您到达此处,则表示您已消耗该事件
返回true;
}
@处理此事件的ranasaha已完成。检查所有与触摸事件相关的代码。仅仅报告Doesent work
对您的问题没有帮助。在向我发布关于该事件的糟糕报告之前,请重新考虑它为什么不起作用。