android – How to detect the direction (left, right, up, down) when moving your finger across the screen (not the coordinates)?

Question:

Hello, I come to seek help with you Programmers since I did not have much that I started in android studio and well, I want to know how I can make an app that when I slide my finger on the screen let's say to the right in a textview it tells me "you textview right" .

The problem is that I don't know how to register, not the touch but the address.

So far the only thing I could do is tell me if I press the screen, if I let go of the screen, I am moving and what coordinates is the place where I am touching.

Could you help me or tell me what to look for? I feel lost

Answer:

I see it much easier: You have to know that the onTouch event is called every time there is an event on the screen. I give you a code example:

public class Ejemplo implements View.OnTouchListener{
    private int firstTouchX;
    private int firstTouchY;
    @Override
    public void onCreate(...){
        //...
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()){
            case MotionEvent.ACTION_DOWN:
                //Aqui guardas en una variable privada de clase las coordenadas del primer toque:
                firstTouchX = event.getX();
                firstTouchY = event.getY(); 
            break;
            case MotionEvent.ACTION_MOVE:
                //Aqui ya podemos determinar los tipos de movimientos:
                if(fistTouchX > event.getX()){
                    //Hacia la izquierda
                }else{
                    //Hacia la derecha
                }
                if(fistTouchY > event.getY()){
                    //Hacia arriba
                }else{
                    //Hacia abajo
                }
            break;
        }
        return true;
    }

I hope to have solved your doubt.

Edited: I have added the return true to the onTouch method. This is important for the ACTION_MOVE otherwise it doesn't work.

Scroll to Top