Search code examples
androidandroid-recyclerviewnestedscrollviewandroid-nestedscrollview

How to scrollTo(x, y) in a RecyclerView inside a NestedScrollView?


Here's my xml code.

    <android.support.v4.widget.NestedScrollView
        android:id="@+id/nav_scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include layout="@layout/nav_header_main" />

            <android.support.v7.widget.RecyclerView
                android:id="@+id/nav_list"
                android:layout_width="match_parent"
                android:layout_height="@dimen/weight_based_height"
                android:layout_weight="1"
                android:nestedScrollingEnabled="false"/>
        </LinearLayout>

    </android.support.v4.widget.NestedScrollView>

I've tried

    navigationScroll.scrollTo(0, 200);
    navigationScroll.smoothScrollTo(0, 200);
    navigationRecycler.scrollTo(0, 200);
    navigationRecycler.smoothScrollTo(0, 200)

and none of them work. Nothing happens, no amount of scroll at all, nada.

But interestingly, when I do this

    navigationScroll.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
        @Override
        public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
            if (scrollY == 0) {
                navigationScroll.scrollTo(0, 150);
            }
        }
    });

The navigationScroll.scrollTo(0, 150); works. How do you guys think I could get it to work without having to put it in a listener?


Solution

  • Okay, my NestedScrollView was inside my DrawerLayout. I got the scrollTo() method to work once I put it inside onDrawerOpened like this.

       toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close){
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
    
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                // Scroll to current item
                navigationScroll.smoothScrollTo(0,200);
            }
    
        };
        drawer.setDrawerListener(toggle);