Pour détecter les mouvements droit et gauche (right to left swipe gestures) :
1°) Créer une classe OnTouchListener :
public class OnTouchListener implements View.OnTouchListener {
ListView list;
private GestureDetector gestureDetector;
private Context context;
public OnSwipeList(Context ctx, ListView list) {
gestureDetector = new GestureDetector(ctx, new GestureListener());
context = ctx;
this.list = list;
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
public void onSwipeLeft(int pos) {
}
public void onSwipeRight(int pos) {
}
private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
private static final int SWIPE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
private int getPostion(MotionEvent e1) {
return list.pointToPosition((int) e1.getX(), (int) e1.getY());
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceX) > Math.abs(distanceY)
&& Math.abs(distanceX) > SWIPE_THRESHOLD
&& Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
onSwipeRight(getPostion(e1));
else
onSwipeLeft(getPostion(e1));
return true;
}
return false;
}
}
}
2°) Utilisation :
lvItems.setOnTouchListener(new OnTouchListener (AfficList.this,lvItems){
public void onSwipeRight(int pos) {
AnnonceDbHandler dbHandler = new AnnonceDbHandler(AfficList.this, null, null, 1);
String sIdAnn=dbHandler.RechercheIdIndex(pos);
//Toast.makeText(AfficList.this, "Right ("+pos+") : "+sIdAnn, Toast.LENGTH_SHORT).show();
dbHandler.deleteAnnonce(sIdAnn, AfficList.this);
Cursor NewCursor = dbAnnonces.rawQuery("SELECT * FROM annonces", null);
todoAdapter.swapCursor(NewCursor);
lvItems.setAdapter(todoAdapter);
todoAdapter.notifyDataSetChanged();
}
public void onSwipeLeft(int pos) {
AnnonceDbHandler dbHandler = new AnnonceDbHandler(AfficList.this, null, null, 1);
String sIdAnn=dbHandler.RechercheIdIndex(pos);
//Toast.makeText(AfficList.this, "Right ("+pos+") : "+sIdAnn, Toast.LENGTH_SHORT).show();
dbHandler.deleteAnnonce(sIdAnn, AfficList.this);
Cursor NewCursor = dbAnnonces.rawQuery("SELECT * FROM annonces", null);
todoAdapter.swapCursor(NewCursor);
lvItems.setAdapter(todoAdapter);
todoAdapter.notifyDataSetChanged();
}
});
Références :
https://guides.codepath.com/android/Gestures-and-Touch-Events#swipe-gesture-detection
Detecting Gesture : http://code.tutsplus.com/tutorials/android-sdk-detecting-gestures–mobile-21161
http://stackoverflow.com/questions/937313/android-basic-gesture-detection
Votre commentaire