I am developing an application with a shop list in a listview. I need that when I swipe the item of listview
to the right(or left), this item should get deleted from the listview.
I have my listview and only need the function to do it.
Thanks in advance.
This is how I realize this effect. We have a ListView lvSimple
and we add onTouchListener to our lvSimple
. This is my working code.
float historicX = Float.NaN, historicY = Float.NaN; static final int DELTA = 50; enum Direction {LEFT, RIGHT;} ... ListView lvSimple = (ListView) findViewById(R.id.linLayout); ... lvSimple.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: historicX = event.getX(); historicY = event.getY(); break; case MotionEvent.ACTION_UP: if (event.getX() - historicX < -DELTA) { FunctionDeleteRowWhenSlidingLeft(); return true; } else if (event.getX() - historicX > DELTA) { FunctionDeleteRowWhenSlidingRight(); return true; } break; default: return false; } return false; } });
where function FunctionDeleteRowWhenSlidingLeft()
is calling when when we sliding to the left, FunctionDeleteRowWhenSlidingRight()
- to the right respectively. In this function you need paste code for animation.
Answer by Android-Developer points to Roman Nurik's code in gist.github.com. This code is out of date. He uses this Swipe to Dismiss listener in his open sourced project Dash Clock.
There are some things you should know, before you use the code in Gist.github.com.
So I recommend using the updated code. You can find the updated source here.
Another option you should consider is to use Tim Roes's EnhancedListView library. [Update - 8/1/2015] With the introduction of RecycleView this library has been deprecated.
The aforementioned Roman Nurik's SwipeToDismiss listener requires API level 12 or higher. Jake Wharton ported this code to support all API levels in SwipeToDismissNOA.
Tim Roes extended this library further to support Undo feature as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With