반응형

It describes how to use the touch API in Android applications.


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
public class MainActivity extends AppCompatActivity {
 
    int x, y;
    TextView textView;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        x = -1;
        y = -1;
        textView = findViewById(R.id.textView);
    }
 
    @Override
    public boolean onTouchEvent(MotionEvent event) {
 
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                x = Math.round(event.getX());
                y = Math.round(event.getY());
                textView.setText("Down position: " + x + ", " + y);
                break;
 
            case MotionEvent.ACTION_MOVE:
                x = Math.round(event.getX());
                y = Math.round(event.getY());
                textView.setText("Move position: " + x + ", " + y);
                break;
 
            case MotionEvent.ACTION_UP:
                x = Math.round(event.getX());
                y = Math.round(event.getY());
                textView.setText("Up position: " + x + ", " + y);
                break;
 
            default:
                break;
        }
 
        return super.onTouchEvent(event);
    }



Run the app and touch the panel.


반응형
Posted by J-sean
: