如何在 NestedScrollView 内的 RecyclerView 中滚动到(x,y)?

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

这是我的 xml 代码。

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

我试过了

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

和 none 有效。没有任何反应,根本没有滚动,nada。

但有趣的是,当我这样做时

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

navigationScroll.scrollTo(0, 150); 有效。你们认为我如何在不将其放入侦听器的情况下让它工作?

您将这些方法放在哪里(即 Activity/Fragment 生命周期方法)?您可能在实际呈现视图之前调用这些方法。在这种情况下,您应该将它们放在不同的生命周期方法中,或者使用 post(Runnable r).

推迟它们

好的,我的 NestedScrollView 在我的 DrawerLayout 里面。一旦我像这样将 scrollTo() 方法放入 onDrawerOpened 中,我就可以使用它了。

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