javaandroidandroid-recyclerviewonscrollchanged

Recycle view onScrollChange listener keep triggering rappedly


I am using the codes below to add vibration effects to Recycle view when I switch items, but I got the vibration to keep triggered the whole time I touch the Recycle View, I want it to activate vibrator only one time when items are changed.

 recyclerView.setOnScrollChangeListener( new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
                Vibrator v = (Vibrator) TeacherMain.this.getSystemService( Context.VIBRATOR_SERVICE);
                v.vibrate(5);}

        } );


Solution

  • You can do as follow:

            mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (SCROLL_STATE_TOUCH_SCROLL == newState) {//when finger touch it.
                    Vibrator v = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
                    v.vibrate(5);
                }
            }
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });