How to implement touch and swipe events in android

I am working on an application in which I implement touch events and events, but now I need to implement an event in which I drag the screen left or right.

Any suggestions..

+4
source share
1 answer

Allows you to select them separately:

Touch events:

Here is a simple example of how to detect a simple touch event, get the coordinates and show a toast.

import android.app.Activity; import android.os.Bundle; import android.view.MotionEvent; import android.widget.Toast; public class MainActivity extends Activity { private boolean isTouch = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onTouchEvent(MotionEvent event) { int X = (int) event.getX(); int Y = (int) event.getY(); int eventaction = event.getAction(); switch (eventaction) { case MotionEvent.ACTION_DOWN: Toast.makeText(this, "ACTION_DOWN AT COORDS "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show(); isTouch = true; break; case MotionEvent.ACTION_MOVE: Toast.makeText(this, "MOVE "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show(); break; case MotionEvent.ACTION_UP: Toast.makeText(this, "ACTION_UP "+"X: "+X+" Y: "+Y, Toast.LENGTH_SHORT).show(); break; } return true; } } 

And if you want to implement horizontal scrolling, you can use this

 private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_OFF_PATH = 250; private static final int SWIPE_THRESHOLD_VELOCITY = 200; int[] values = new int[] { R.drawable.image1, R.drawable.image2, R.drawable.image3 }; @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { try { if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) { return false; } /** * left to right swipe */ if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { //next image setImage(image+1); /** * right to left */ } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { //prev image setImage(image-1); } } catch (Exception e) { } return false; } 
+3
source

Source: https://habr.com/ru/post/1493795/


All Articles