I implemented RecyclerView. I would like a view scroll to top of item on 5th position in RecyclerView. scrollToPosition(5)
don't work
XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="128dp"
android:orientation="vertical">
<androidx.core.widget.NestedScrollView
android:id="@+id/nestedScrollView_mark"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="@+id/linearLayout_markView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView_marks"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp" />
<LinearLayout
android:id="@+id/linearLayout_behavior"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="@drawable/layout_bg"
android:orientation="vertical"
android:visibility="invisible">
in Fragment:
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.getLayoutManager().scrollToPosition(5);
recyclerView.setAdapter(adapter);
The scrollToPosition()
needs to be used with any of the following ways to restore the scroll position to the selected position.You can save the selected position in onPause()
and then restore subsequently. There might be two useful ways :-
onSaveInstanceState()
function to save the state as explained here .onCreateView
.
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.