Android事件分发机制初探
Android的触摸事件分发是从最上层的Activity开始的,然后dispatch到子View,当分发到触发事件的View时,再逐层往回调用onTouchEvent函数,下面是实例代码。(有空还要更彻底的研究下源码)
1 public class DispatchActivity extends Activity {
2
3 @Override
4 protected void onCreate(Bundle savedInstanceState) {
5 super.onCreate(savedInstanceState);
6
7 View disView = new DispatchView(this);
8 LayoutParams lp = new LayoutParams(LayoutParams.FILL_PARENT,
9 LayoutParams.FILL_PARENT);
10 setContentView(disView, lp);
11 }
12
13 @Override
14 public boolean onTouchEvent(MotionEvent event) {
15 if (event.getAction() == MotionEvent.ACTION_DOWN) {
16 Log.i("()()", "Parent onTouchEvent Down!!!!!!!!!!!!!!!!");
17 }
18 return super.onTouchEvent(event);
19 }
20
21 @Override
22 public boolean dispatchTouchEvent(MotionEvent ev) {
23 if (ev.getAction() == MotionEvent.ACTION_DOWN) {
24 Log.i("()()", "Parent dispatchTouchEvent Down????????????????");
25 }
26 return super.dispatchTouchEvent(ev);
27 }
28
29 public class DispatchView extends View {
30
31 private Paint paint = new Paint();
32
33 public DispatchView(Context context) {
34 super(context);
35 paint.setColor(Color.RED);
36 }
37
38 @Override
39 public boolean dispatchTouchEvent(MotionEvent event) {
40 if (event.getAction() == MotionEvent.ACTION_DOWN) {
41 Log.i("()()", "Child dispatchTouchEvent Down#############");
42 paint.setColor(Color.BLUE);
43 invalidate();
44 }
45 return super.dispatchTouchEvent(event);
46 }
47
48 @Override
49 public boolean onTouchEvent(MotionEvent event) {
50 if (event.getAction() == MotionEvent.ACTION_DOWN) {
51 Log.i("()()", "Child onTouchEvent Down*****************");
52 paint.setColor(Color.GREEN);
53 invalidate();
54 }
55 return super.onTouchEvent(event);
56 }
57
58 @Override
59 protected void onDraw(Canvas canvas) {
60 canvas.drawRect(30, 30, 300, 300, paint);
61 super.onDraw(canvas);
62 }
63
64 }
65
66 }
实例效果如下:
当点击红色的View时,log如下:
如果Child View设置了OnClickListener,那么和在Child View的onTouchEvent函数中返回True是一个效果,也就是此事件不再向上传播。