Search code examples
javaandroidswipegestureontouchlistener

Scroll to top of next item in a recyclerview


I have the following code which detects that whether a swipe in onTouch is Left / Right. But i want to detect top/down. Please suggest changes in the code as to how i can achieve that by modifying the code

r.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            int downX = 0,upX;
            switch(event.getAction()){
                case MotionEvent.ACTION_DOWN:{
                    downX = (int) event.getX();}
                case MotionEvent.ACTION_UP:{
                    upX = (int) event.getX();

                    float deltaX = downX - upX;
                    Log.e("DeltaX","Dd "+deltaX);
                     if(Math.abs(deltaX)>0){
                        if(deltaX>=0){

                            return true;
                        }else{

                            return  true;
                        }
                    }
                    else {

                    }
                }
            }

            return false;
        }
    });

Please dont suggest any 3 rd party libraries or any other solution. Please suggest changes in the above code only. I have tried a lot of other things, but this is a perfect fit

Thank you for responding!


Solution

  • here is the code i figured out

      r.addOnScrollListener(new RecyclerView.OnScrollListener() {
            public boolean top;
    
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
    
    
                if (top) {
                    int index = mLay.findFirstVisibleItemPosition();
                    r.smoothScrollToPosition(index);
    
                } else {
                    int index = mLay.findLastVisibleItemPosition();
                    r.smoothScrollToPosition(index);
    
    
                }
    
    
            }
    
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
    
                if (dy > 0) {
                    top = false;
                } else {
    
                    top = true;
                }
    
            }
        });