这几天遇到点关于Android的触摸事件相关的,还跟onClick有关,暂且记下:
LinearLayout分别设置了onTouchListener,onClickListener,onLongClickListener及onTouchEvent回调
1、在屏幕上触摸之后基本的执行流程如下:
onTouch,action=0
onTouchEvent,action=0
onTouch,action=2
onTouchEvent,action=2
onTouch,action=2
onTouchEvent,action=2
onTouch,action=1
onTouchEvent,action=1
onClick
也就是先说onTouchListener是最先被触发的,然后是本身的onTouchEvent回调;当最后的up事件发生并被onTouchEvent处理后才会触发onClickListener。
2、把onTouchEvent回调中的super.onTouchEvent去除,直接返回true;则流程如下:
onTouch,action=0
onTouchEvent,action=0
onTouch,action=2
onTouchEvent,action=2
onTouch,action=2
onTouchEvent,action=2
onTouch,action=1
onTouchEvent,action=1
可以看到onClickListener永远无法被触发,也侧面说明了对onClick的触发是在onTouchEvent回调中来实现的。
3、长按屏幕,流程如下:
onTouch,action=0
onTouchEvent,action=0
onTouch,action=2
onTouchEvent,action=2
onTouch,action=2
onTouchEvent,action=2
onLongClick
onTouch,action=2
onTouchEvent,action=2
onTouch,action=2
onTouchEvent,action=2
onTouch,action=1
onTouchEvent,action=1
onClick
当长按的时候,无需到up就会触发onLongClick的响应,但之后也会继续触发onClick的响应。
4、但如果在onLongClick中返回true,则流程如下,即只在中间触发了onLongClick,之后会继续响应touch,但当up的时候就不会再触发onClick
onTouch,action=0
onTouchEvent,action=0
onTouch,action=2
onTouchEvent,action=2
onTouch,action=2
onTouchEvent,action=2
onLongClick
onTouch,action=2
onTouchEvent,action=2
onTouch,action=2
onTouchEvent,action=2
onTouch,action=1
onTouchEvent,action=1
测试代码如下:
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); FrameLayout frame = (FrameLayout)findViewById(R.id.container); LinearLayoutTest line = new LinearLayoutTest(this); line.setOnClickListener(new ClickListener()); line.setOnLongClickListener(new LongClickListener()); line.setOnTouchListener(new TouchListener()); line.setLongClickable(true); frame.addView(line); } public class ClickListener implements OnClickListener { @Override public void onClick(View v) { Log.e("test","onClick"); } } public class LongClickListener implements OnLongClickListener{ @Override public boolean onLongClick(View v) { Log.e("test","onLongClick"); return true; } } public class TouchListener implements OnTouchListener{ @Override public boolean onTouch(View v, MotionEvent event) { Log.e("test","onTouch,action="+event.getAction()); return false; } } }
原文:http://www.cnblogs.com/colife/p/4504806.html