之前一段时间写android程序的时候只管调用某个view的ontouch函数,直接使用eclipse自动提示打出的返回值用,也没在意返回值真假有什么意义,突然有一天在做方向按钮的时候,发现用了view的ontouch函数后一直检测不到action_up这个动作,没明白怎么回事,一直都挺好的,怎么就出问题了。

查了下资料,解决了这个问题,下面说说自己的见解。

android里有一个activity的大view,而一个button就相当于activity里面的一个小view,android对用户touch的响应,是这样子的,activity里面有一个onTouchEvent是用来响应用户touch屏幕时activity的处理,而对button设置了监听ontouchlistener,则会调用监听函数里的ontouch函数,在touch的的操作不在button上的时候,android会先调用activity的ontouchevent事件进行响应,而当touch在button上的时候,系统会优先执行button的监听函数的ontouch事件,而系统会根据ontouch函数的返回值来确定是不是要把接下来的事件传给activity的onTouchEvent进行处理。

而在ontcouh返回true的时候就是说我希望不把ontouch事件的处理权交给activity的ontcouhevent函数处理。

而在ontouch返回false的时候就是说我要把ontouch事件处理完之后把touch的处理权交给activity的ontcouhevent函数处理。

拿我遇到的问题来解释就是,我的action_up事件没法响应,因为我返回的是false。也就是说,在我的touch里面有switch case 当我执行完down这个动作的时候ontouch函数会返回一个值false,这时候activity的ontouchevent事件就来接管这次ontouch的处理权,这样我down完之后的up动作其实是交给ontouchevent的action_up处理了,也就没执行我的ontouch函数里的action_up这个情况。而把返回值改成true,则这次touch的处理仍然是由ontouch来处理,不会回到ontouchevent处理。这就是为什么我的action_up这个动作在返回false时没执行,其实它是去执行了activity的ontouchevent函数里的action_up。

代码演示:

activity里面重写了

@Override
public boolean onTouchEvent(MotionEvent event) {

switch (event.getAction()) {
case MotionEvent.ACTION_UP:
Log.d("Test", "up in activity!");
break;
default:
break;
}

  而对一个button设置监听函数 mbutton.ssetOnTouchListener(new TestTouchListener());

public class PTZDirectionListener implements OnTouchListener {
@Override
public boolean onTouch(View v, MotionEvent event) {

case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
Log.d("Test", "up in ontouch!!");

break;


default:
break;
}
return true;
}}

注意在ontouch的return为true的时候,编译后打印的结果是up in ontouch.

而return为false的时候,编译后打印的结果是up in activity。

有什么说的不对的大家请见而诛之。