Home » Android » android – Disable NestedScrollview scroll

android – Disable NestedScrollview scroll

Posted by: admin June 15, 2020 Leave a comment

Questions:

Design of my app

Screen – 1

    <NestedScrollview>
       <LinearLayout orientation:horizontal">
          <RecyclerView-1>
          <Framelayout>(contains Recyclerview-2)
    </NestedScroll>

Screen – 2

     <NestedScrollview>
         <LinearLayout orientation:horizontal">
         <RecyclerView-1>
         <Framelayout> (fragment changed, contains Recyclerview-3)
     </NestedScroll>

Now if user is on screen 1, then both the recyclerview will scroll simultaneously, but on screen 2 if user scrolls RV1 then only RV1 will scroll similarly if RV3 is scrolled then RV3 will be scrolled. Tried all sort of stop scroll, but unable to stop scroll of nested scrollview.

How to&Answers:

You must to create a new class that do nothing on touch and scroll events:

public class LockableNestedScrollView extends NestedScrollView {
    // by default is scrollable
    private boolean scrollable = true;

    public LockableNestedScrollView(@NonNull Context context) {
        super(context);
    }

    public LockableNestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public LockableNestedScrollView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        return scrollable && super.onTouchEvent(ev);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        return scrollable && super.onInterceptTouchEvent(ev);
    }

    public void setScrollingEnabled(boolean enabled) {
        scrollable = enabled;
    }
}

Next in your layout you change the NestedScroll by your new class:

    <your.package.name.path.LockableNestedScrollView>
       <LinearLayout 
          orientation:"horizontal"
          android:id="@+id/scroll_name">
          <RecyclerView-1>
          <Framelayout>(contains Recyclerview-2)
    </your.package.name.path.LockableNestedScrollView>

Finally in your activity:

LockableNestedScrollView myScrollView = (LockableNestedScrollView) findViewById(R.id.scroll_name);
myScrollView.setScrollingEnabled(false);

I hope it helps someone else.