Remove item listview with Slide - Like Gmail

dmontielfdez picture dmontielfdez · Jan 18, 2013 · Viewed 58.3k times · Source

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.

Answer

macloving picture macloving · Apr 10, 2013

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.