【问题标题】:How to scrollTo(x, y) in a RecyclerView inside a NestedScrollView?如何在 NestedScrollView 内的 RecyclerView 中滚动到(x,y)?
【发布时间】:2016-12-03 12:48:38
【问题描述】:

这是我的 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)

它们都不起作用。什么都没有发生,根本没有滚动,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); 有效。你们认为我怎样才能让它工作而不必把它放在监听器中?

【问题讨论】:

标签: android android-recyclerview nestedscrollview android-nestedscrollview


【解决方案1】:

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

【讨论】:

  • 我最终想通了,但感谢您的意见!
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-01
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-25
    • 2021-12-10
    相关资源
    最近更新 更多