ABHI
ABHI

Reputation: 121

How to implement touch and swipe events in android

I am working on an application where I am implementing touch events and swipe events but now I need to implement an event where I am dragging the screen left or right..

Any suggestions..

Upvotes: 4

Views: 8548

Answers (1)

MSA
MSA

Reputation: 2482

Lets take them separate:

Touch Events:

Here is a simple example on how to detect a simple on touch event, get coords 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 swipe 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;
}

Upvotes: 3

Related Questions