简体   繁体   中英

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?

Where did you put those methods (ie in which Activity / Fragment lifecycle method)? It is possible that you are calling those methods before the view is actually rendered. In this case, you should put those in a different lifecycle method, or postpone them with a post(Runnable r) .

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM