Reprinted from: http://blog.csdn.net/qiantujava/article/details/9903891
Use Activity's onTouchEvent method to monitor finger sliding up, down, left and right
The ontouchEvent method of Activity is applied to monitor the finger click event. When the finger slides, it will be pressed first, slipped to another place and then lifted. We can calculate which direction the user is sliding according to the coordinates of the pressed and lifted coordinates. .
- package com.example.testtt;
- import android.app.Activity;
- import android.os.Bundle;
- import android.view.MotionEvent;
- import android.widget.Toast;
- publicclass MainActivity extends Activity {
- //The point where the finger is pressed is (x1, y1) The point where the finger leaves the screen is (x2, y2)
- float x1 = 0;
- float x2 = 0;
- float y1 = 0;
- float y2 = 0;
- @Override
- protectedvoid onCreate(Bundle savedInstanceState) {
- super .onCreate (savedInstanceState);
- setContentView(R.layout.activity_main);
- }
- @Override
- publicboolean onTouchEvent(MotionEvent event) {
- //Inherited Activity's onTouchEvent method, directly listening for click events
- if(event.getAction() == MotionEvent.ACTION_DOWN) {
- // when the finger is pressed
- x1 = event.getX();
- y1 = event.getY();
- }
- if(event.getAction() == MotionEvent.ACTION_UP) {
- // when the finger leaves
- x2 = event.getX();
- y2 = event.getY();
- if(y1 - y2 > 50) {
- Toast.makeText(MainActivity.this, "向上滑", Toast.LENGTH_SHORT).show();
- } else if(y2 - y1 > 50) {
- Toast.makeText(MainActivity.this, "向下滑", Toast.LENGTH_SHORT).show();
- } else if(x1 - x2 > 50) {
- Toast.makeText(MainActivity.this, "向左滑", Toast.LENGTH_SHORT).show();
- } else if(x2 - x1 > 50) {
- Toast.makeText(MainActivity.this, "向右滑", Toast.LENGTH_SHORT).show();
- }
- }
- returnsuper.onTouchEvent(event);
- }
- }