ilan
ilan

Reputation: 4462

Swipeable listview

I need to implement a list view that when swiping a row to one side all the other rows will swipe to the other side. All of my rows will be on screen(.2-7 rows.)

I know I can get the views in the adapter. But how can I get the touched view ( not clicked).

I am not really sure how to start implementing this.

Any suggestions??

Thanks, Ilan

Upvotes: 0

Views: 163

Answers (1)

Riley van Hengstum
Riley van Hengstum

Reputation: 4552

You can use View.setOnTouchListener(..) for that.

Here is some example code:

public class SwipeTouchListener implements View.OnTouchListener {
    private ListView listView;
    private View downView;

    public SwipeTouchListener(ListView listView) {
        this.listView = listView;
    }

    @Override
    public boolean onTouch(View v, MotionEvent motionEvent) {
        switch (motionEvent.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                // swipe started, get reference to touched item in listview
                downView = findTouchedView(motionEvent);
                break;
            case MotionEvent.ACTION_MOVE:
                if (downView != null) {
                    // view is being swiped
                }
                break;
            case MotionEvent.ACTION_CANCEL:
                if (downView != null) {
                    // swipe is cancelled
                   downView = null;
                }    

                break;
            case MotionEvent.ACTION_UP:
                if (downView != null) {
                    // swipe has ended
                   downView = null;
                }               
                break;
            }
        }
    }

    private View findTouchedView(MotionEvent motionEvent) {
        Rect rect = new Rect();
        int childCount = listView.getChildCount();
        int[] listViewCoords = new int[2];
        listView.getLocationOnScreen(listViewCoords);
        int x = (int) motionEvent.getRawX() - listViewCoords[0];
        int y = (int) motionEvent.getRawY() - listViewCoords[1];
        View child = null;
        for (int i = 0; i < childCount; i++) {
            child = listView.getChildAt(i);
            child.getHitRect(rect);
            if (rect.contains(x, y)) {
                break;
            }
        }

        return child;
    }
}

To use this:

SwipeTouchListener swipeTouchListener = new SwipeTouchListener(listView);
listView.setOnTouchListener(swipeTouchListener);

Upvotes: 1

Related Questions