Detect Touch Event, test on Custom View; part II.
Following the former post "Detect Touch Event, test on Custom View". In order to trace the trigged MotionEvent in onTouchEvent(), it's modified to have a TextView to display the event.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
| package com.TestSingleTouch;import android.app.Activity;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.os.Bundle;import android.view.MotionEvent;import android.view.View;import android.widget.LinearLayout;import android.widget.TextView;public class TestSingleTouch extends Activity { public class TouchView extends View { private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); private float x, y; boolean touching = false; public TouchView(Context context) { super(context); // TODO Auto-generated constructor stub } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub if(touching){ paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(1); paint.setColor(Color.WHITE); canvas.drawCircle(x, y, 50f, paint); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), MeasureSpec.getSize(heightMeasureSpec)); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub String act; int action = event.getAction(); switch(action){ case MotionEvent.ACTION_MOVE: act = "ACTION_MOVE\n"; x = event.getX(); y = event.getY(); touching = true; break; case MotionEvent.ACTION_DOWN: act = "ACTION_DOWN\n"; x = event.getX(); y = event.getY(); touching = true; break; case MotionEvent.ACTION_UP: act = "ACTION_UP\n"; touching = false; break; default: act = "XXX\n"; touching = false; } act += event.toString(); textView.setText(act); invalidate(); return true; } } TextView textView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(new TouchView(this)); textView = new TextView(this); textView.setText("Waiting"); TouchView touchView = new TouchView(this); LinearLayout mainScreen = new LinearLayout(this); mainScreen.setOrientation(LinearLayout.VERTICAL); mainScreen.addView(textView); mainScreen.addView(touchView); setContentView(mainScreen); }}akmwww.cdacians.com |
No comments:
Post a Comment