I am trying to swipe a row in my ListView, identify its text and perform certain actions. I am able to detect left/right swipes but how to I go about identifying the text for that swiped row? I am not able to identify its location unlike using onItemClickListener where I could use the position variable.
MainActivity Class
ListView orderListView;
ArrayList<String> orders;
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_stock);
orderListView = (ListView)findViewById(R.id.orderListView);
orders = new ArrayList<>();
orders.add("order 1");
orders.add("order 2");
orders.add("order 3");
adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, orders);
orderListView.setAdapter(adapter);
OnSwipeTouchListener onSwipeTouchListener = new OnSwipeTouchListener(this, orderListView);
orderListView.setOnTouchListener(onSwipeTouchListener);
}
OnSwipeTouchListener Class
public class OnSwipeTouchListener implements View.OnTouchListener {
ListView list;
private GestureDetector gestureDetector;
private Context context;
public OnSwipeTouchListener(Context ctx, ListView list) {
gestureDetector = new GestureDetector(ctx, new GestureListener());
context = ctx;
this.list = list;
}
public OnSwipeTouchListener() {
super();
}
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
public void onSwipeRight(int pos) {
Log.i("zxR", "right");
}
public void onSwipeLeft() {
Log.i("zxL", "left");
}
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();
return true;
}
return false;
}
}
}