Search code examples
androidandroid-listfragmentgesturedetector

Gesture Detection in ListFragment


I have a ListFragment that I populate with a ContentProvider.

I need to attach a gesture listener to each of them so that when the user swipes to right, the item is removed from the list.

Below is all I have in my ListFragment at the moment.

@Override
public void onListItemClick(ListView l, View v, int position, long id) {

 String selection = l.getItemAtPosition(position).toString();
 Toast.makeText(v.getContext(), selection + "", Toast.LENGTH_LONG).show();
 Log.d("TodoListFragment", selection+ "");

}

How would I attach the gesture detection and listening?

I have done some research and found this piece of code:

class MyGestureDetector extends SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        try {
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
            // right to left swipe
            if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
               Log.d("Swipe", "Left");
            }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                Log.d("Swipe", "Right");
            }
        } catch (Exception e) {
            // nothing
        }
        return false;
    }

}

Can anyone tell me how to implement it? (Not the deleting part but just the implementation)


Solution

  • I faced some problem throughout i fixed issue using below answer.

    it works perfectly.

    class SideIndexGestureListener extends GestureDetector.SimpleOnGestureListener {
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
    
                Log.d("Scrolled- fragment ", "Scrolling");
                return super.onScroll(e1, e2, distanceX, distanceY);
            }
        }
    
    
    
    
        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);
    
            final GestureDetector gestureDetector = new GestureDetector(getActivity(),
                    new SideIndexGestureListener());
            View.OnTouchListener gestureListener = new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    return gestureDetector.onTouchEvent(event);
                }
            };
            getListView().setOnTouchListener(gestureListener);
            try {
    
               adapter = new ArrayAdapter<String>(getActivity(),
                        android.R.layout.simple_list_item_single_choice, elementos);
                setListAdapter(adapter);
                getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    
            }catch (Exception e){
    
            }