web-dev-qa-db-fra.com

Ajout du geste Fling à une vue d'image - Android

D'accord j'ai référencé le code ici: Détection de geste Fling sur la disposition de la grille

mais ne peut tout simplement pas le faire fonctionner. Dans mon activité principale, une image simple est définie. Je veux détecter un fling sur l'image. Voici mon code ci-dessous. La méthode onclick en bas est vide. Est-ce à cause de cela? Je l'ai laissé en blanc parce que dans l'autre exemple de code, ce n'est pas ce que je veux. Je veux juste qu'un simple toast apparaisse en disant: jetez à droite ou jetez à gauche.

public class GestureRightLeft extends Activity implements OnClickListener  {

    ImageView peek;

    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;
    private GestureDetector gestureDetector;
    View.OnTouchListener gestureListener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        peek =(ImageView) findViewById(R.id.peek);
        peek.setImageResource(R.drawable.bluestrip);

        gestureDetector = new GestureDetector(new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if (gestureDetector.onTouchEvent(event)) {
                    return true;
                }
                return false;
            }
        };
    }

    class MyGestureDetector extends SimpleOnGestureListener {
        @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;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    Toast.makeText(GestureRightLeft.this, "Left Swipe", Toast.LENGTH_SHORT).show();
                }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    Toast.makeText(GestureRightLeft.this, "Right Swipe", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                // nothing
            }
            return false;
        }
    }

    @Override
    public void onClick(View v) {}
}
45
Ryan

Voici la version la plus simple de travail de flinger à laquelle je puisse penser ... vous pouvez la lier à n’importe quel composant, pas seulement à ImageView.

public class MyActivity extends Activity {
    private void onCreate() {
        final GestureDetector gdt = new GestureDetector(new GestureListener());
        final ImageView imageView  = (ImageView) findViewById(R.id.image_view);
        imageView.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(final View view, final MotionEvent event) {
                gdt.onTouchEvent(event);
                return true;
            }
        });
    }               

    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;

    private class GestureListener extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                return false; // Right to left
            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                return false; // Left to right
            }

            if(e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                return false; // Bottom to top
            }  else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                return false; // Top to bottom
            }
            return false;
        }
    }
}

Aucune activité sur onClickListener cependant (si vous n’avez besoin d’attraper aucune action onclick). peut voir . Dans les endroits où la méthode retourne (et où sont mes commentaires), appelez simplement votre méthode ou quoi que ce soit :)

87
Alex Orlov

Essaye ça 

imageView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return false;
            }
            return true;
        }
  });
13
Pavan
imageView.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return !gestureDetector.onTouchEvent(event);
    }
});
10
Magublafix

certaines des conditions préalables

1)setonClick method
     image.setOnClickListener(this);

2)set your gesture detection in onTouch()
    image.setOnTouchListener(new OnTouchListener() {
         GestureDetector gestureDetector = new GestureDetector(new SwingGestureDetection((mContext),image,a));
         @Override
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
         }
     });

3)create SwingGestureDetection class and implement all method
@Override
public boolean onFling(MotionEvent start, MotionEvent finish, float arg2,float arg3) {
    if(start.getRawX()<finish.getRawX()){
        System.out.println("next...swing");
    }else{
    System.out.println("previois...swing");


}

4)pass your imageview in constructor
public SwingGestureDetection(Context con,ImageView image,int pos) {
    mContext=con;
    this.image=image;
    this.position=pos;
}

C’est un travail parfait pour moi.

3
Harshid

Essayez de lire: http://illusionsandroid.blogspot.com/2011/05/adding-fling-gesture-listener-to-view.html

Il vous permet de séparer la mise en œuvre de votre activité de votre écouteur personnalisé. C'est simplement une refactorisation de la solution rapportée par Alex Orlov

2
alessio.cocciolo

Si vous recherchez une méthode comme ImageView.setOnGestureListener, il n'y en a pas. Vous pouvez aller voir le code source Android. Votre meilleure option est de le gérer dans onTouch () de l'objet View. 

C'est le plus simple GestureDetector que je puisse faire. 

J'ai une classe appelée GenesMotionDetector.Java. Voici le code pour cela:

package gene.com.motioneventssample;

import Android.app.Activity;
import Android.os.Bundle;
import Android.view.GestureDetector;
import Android.view.MotionEvent;
import Android.widget.ImageView;
import Android.widget.LinearLayout;
import Android.widget.TextView;

public class GenesMotionDetector extends Activity implements GestureDetector.OnGestureListener {
    private GestureDetector gestureScanner;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nothing);
        gestureScanner= new GestureDetector(getBaseContext(),this);
    }

    @Override
    public boolean onTouchEvent(MotionEvent me) {
        System.out.println("Inside onTouchEvent() of GenesMotionDetector.Java");
        return gestureScanner.onTouchEvent(me);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        System.out.println("Inside onDown() of GenesMotionDetector.Java");
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        System.out.println("Inside onFling() of GenesMotionDetector.Java");
        return true;
    }

    @Override
    public void onLongPress(MotionEvent e) {
        System.out.println("Inside onLongPress() of GenesMotionDetector.Java");
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        System.out.println("Inside onScroll() of GenesMotionDetector.Java");
        return true;
    }

    @Override
    public void onShowPress(MotionEvent e) {
        System.out.println("Inside onShowPress() of GenesMotionDetector.Java");
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        System.out.println("Inside onSingleTapUp() of GenesMotionDetector.Java");
        return true;
    }
}

Le fichier de mise en page XML correspondant à cette classe est Nothing.xml. Voici le code pour cela:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    Android:id="@+id/screen"
    Android:orientation="vertical" Android:layout_width="match_parent"
    Android:layout_height="match_parent">

    <TextView
        Android:id="@+id/text"
        Android:background="#17528c"
        Android:text="testing"
        Android:layout_width="100dp"
        Android:layout_height="200dp" />

    <ImageView
        Android:id="@+id/image"
        Android:background="#f8af20"
        Android:layout_width="100dp"
        Android:layout_height="200dp" />
</LinearLayout>

Maintenant, en prenant le plus simple GestureDetector que je peux faire (d’en haut) et en le modifiant comme vous le souhaitez, j’obtiens ceci:

package gene.com.motioneventssample;

import Android.app.Activity;
import Android.os.Bundle;
import Android.view.GestureDetector;
import Android.view.MotionEvent;
import Android.view.VelocityTracker;
import Android.view.View;
import Android.widget.ImageView;

public class GenesMotionDetector3 extends Activity implements GestureDetector.OnGestureListener {
    private GestureDetector gestureScanner;
    ImageView mView3;

    View.OnTouchListener gestureListener;
    MotionEvent initialME, finalME;
    private VelocityTracker mVelocityTracker = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nothing);


        mView3 = (ImageView) findViewById(R.id.image);

        // Gesture detection
        gestureScanner = new GestureDetector(getBaseContext(), this);

        gestureListener = new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch(event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        initialME= event;

                        if(mVelocityTracker == null) {
                            // Retrieve a new VelocityTracker object to watch the velocity of a motion.
                            mVelocityTracker = VelocityTracker.obtain();
                        }
                        else {
                            // Reset the velocity tracker back to its initial state.
                            mVelocityTracker.clear();
                        }
                        // Add a user's movement to the tracker.
                        mVelocityTracker.addMovement(event);

                        break;
                    case MotionEvent.ACTION_MOVE:
                        mVelocityTracker.addMovement(event);
                        // When you want to determine the velocity, call
                        // computeCurrentVelocity(). Then call getXVelocity()
                        // and getYVelocity() to retrieve the velocity for each pointer ID.
                        mVelocityTracker.computeCurrentVelocity(1000);
                        break;
                    case MotionEvent.ACTION_UP:
                        finalME=event;
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        // Return a VelocityTracker object back to be re-used by others.
                        mVelocityTracker.recycle();
                        break;
                }
                return onFling(initialME, finalME, mVelocityTracker.getXVelocity(), mVelocityTracker.getYVelocity());
                //return false;
            }
        };

        mView3.setOnTouchListener(gestureListener);
    }

    @Override
    public boolean onTouchEvent(MotionEvent me) {
        System.out.println("Inside onTouchEvent() of GenesMotionDetector.Java");

        return gestureScanner.onTouchEvent(me);
    }

    @Override
    public boolean onDown(MotionEvent e) {
        System.out.println("Inside onDown() of GenesMotionDetector.Java");
        return true;
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        System.out.println("Inside onFling() of GenesMotionDetector.Java");
        System.out.println("e1= "+ e1);
        System.out.println("e2= "+ e2);
        System.out.println("velocityX= "+ velocityX);
        System.out.println("velocityY= "+ velocityY);
        return true;
    }

    @Override
    public void onLongPress(MotionEvent e) {
        System.out.println("Inside onLongPress() of GenesMotionDetector.Java");
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        System.out.println("Inside onScroll() of GenesMotionDetector.Java");
        return true;
    }

    @Override
    public void onShowPress(MotionEvent e) {
        System.out.println("Inside onShowPress() of GenesMotionDetector.Java");
    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        System.out.println("Inside onSingleTapUp() of GenesMotionDetector.Java");
        return true;
    }
}

Vous pourriez aussi bien tout gérer dans onTouch (). En gros, je saisis les gestes dans onTouch et les passe à onFling (). 

0
Gene

Créez votre mise en page avec ImageView . Ajoutez setOnTouchListenerà imageView .imageview.setOnTouchListener(this). Ajoutez une méthode non implémentée View.OnTouchListener. Ensuite, vous pouvez implémenter votre méthode onTouch dans votre logique d’invité.

float x1,x2;
float y1, y2;

@Override
public boolean onTouch(View view, MotionEvent event) {
    switch ( event.getAction() ){

        case MotionEvent.ACTION_DOWN:{
            x1 = event.getX();
            y1 = event.getY();
            break;
        }

        case MotionEvent.ACTION_UP:{
            x2 = event.getX();
            y2 = event.getY();

            if ( x1<x2 ) {
                //implement what you need to do here
            }
            if ( x1>x2 ) {
                //implement what you need to do here
            }
            break;
        }
    }
    return false;
}
0
Ashana.Jackol

Si vous n'aimez pas créer une classe séparée ou rendre le code complexe,
Vous pouvez simplement créer une variable GestureDetector dans OnTouchListener et rendre votre code plus simple.

namVyuVar peut être n'importe quel nom de la vue sur laquelle vous devez définir le listner.

namVyuVar.setOnTouchListener(new View.OnTouchListener()
{
    @Override
    public boolean onTouch(View view, MotionEvent MsnEvtPsgVal)
    {
        flingActionVar.onTouchEvent(MsnEvtPsgVal);
        return true;
    }

    GestureDetector flingActionVar = new GestureDetector(getApplicationContext(), new GestureDetector.SimpleOnGestureListener()
    {
        private static final int flingActionMinDstVac = 120;
        private static final int flingActionMinSpdVac = 200;

        @Override
        public boolean onFling(MotionEvent fstMsnEvtPsgVal, MotionEvent lstMsnEvtPsgVal, float flingActionXcoSpdPsgVal, float flingActionYcoSpdPsgVal)
        {
            if(fstMsnEvtPsgVal.getX() - lstMsnEvtPsgVal.getX() > flingActionMinDstVac && Math.abs(flingActionXcoSpdPsgVal) > flingActionMinSpdVac)
            {
                // TskTdo :=> On Right to Left fling

                return false;
            }
            else if (lstMsnEvtPsgVal.getX() - fstMsnEvtPsgVal.getX() > flingActionMinDstVac && Math.abs(flingActionXcoSpdPsgVal) > flingActionMinSpdVac)
            {
                // TskTdo :=> On Left to Right fling

                return false;
            }

            if(fstMsnEvtPsgVal.getY() - lstMsnEvtPsgVal.getY() > flingActionMinDstVac && Math.abs(flingActionYcoSpdPsgVal) > flingActionMinSpdVac)
            {
                // TskTdo :=> On Bottom to Top fling

                return false;
            }
            else if (lstMsnEvtPsgVal.getY() - fstMsnEvtPsgVal.getY() > flingActionMinDstVac && Math.abs(flingActionYcoSpdPsgVal) > flingActionMinSpdVac)
            {
                // TskTdo :=> On Top to Bottom fling

                return false;
            }
            return false;
        }
    });
});
0
Sujay U N