简体   繁体   中英

NestedScrollView smooth scroll to the top and to a view inside

First I need to scroll my NestedScrollView to the top, but smoothScrollTo(0, 0) doesn't work for me (page just jumping a bit). Second I wonder how can I scroll to a certain view inside my NestedScrollView . API 27, Support 27.0.2.

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">

    <data/>

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

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/PageBackground"
            android:fillViewport="true">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:descendantFocusability="blocksDescendants"
                android:orientation="vertical"
                android:paddingBottom="@dimen/indent_page_bottom">

                ...

                <android.support.v7.widget.RecyclerView
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical" />

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

</layout>

I had a nestedscrollview and inside it there is recyclerview . I tried smoothScrollTo(0, nsv_main.top) . Didn't work. I gave an id to nestedscrollview like below

<android.support.v4.widget.NestedScrollView
    android:id="@+id/nsv_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/PageBackground"
    android:fillViewport="true">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:descendantFocusability="blocksDescendants"
        android:orientation="vertical"
        android:paddingBottom="@dimen/indent_page_bottom">

        ...

        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />

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

and gave nsv_main.scrollY = 0 in my click event. It worked, even though its not a smooth scroll.

Try using fling to achieve smooth scrolling :

nestedScrollView.fling(0);
nestedScrollView.smoothScrollTo(0, 0);

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