6

What I want : To save the scroll position of the collapsing toolbar when switching fragments.

Right now the toolbar recreates and doesn't save the last scrolled position but recyclerView does. How to save the collapsing toolbar scroll position?

Layout.xml

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/f_c_coordinator_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:id="@+id/f_c_app_bar_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:fitsSystemWindows="true">

    <android.support.design.widget.CollapsingToolbarLayout
        android:id="@+id/f_c_collapsing_toolbar"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:titleEnabled="false"
        app:layout_scrollFlags="scroll">

        <android.support.v7.widget.Toolbar
            android:id="@+id/f_c_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:titleTextColor="@android:color/white"
            app:layout_scrollFlags="scroll|enterAlways"
            app:layout_collapseMode="parallax"
            android:fitsSystemWindows="true"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Dark"/>

    </android.support.design.widget.CollapsingToolbarLayout>

</android.support.design.widget.AppBarLayout>

<android.support.v7.widget.RecyclerView
....
/>

</android.support.design.widget.CoordinatorLayout>
Ansh
  • 365
  • 6
  • 19

3 Answers3

8

After looking couple of days into StackOverflow, I actually found the solution.

I'm not sure what's causing the issue but CollapsingToolbar save it'scroll position when switching between activities. This issue occures while working with Fragments using FragmentTransaction.

To save the scrolled state of CollpasingToolbar add this line to fragment onViewCreated() method.

ViewCompat.requestApplyInsets(mCoordinatorLayout); // pass the coordinatorlayout id.

If one could explain the exact reason what's the reason behind the issue then please free to comment.

Ansh
  • 365
  • 6
  • 19
6

You can preserve the scroll position by simply adding the id attr:

<androidx.coordinatorlayout.widget.CoordinatorLayout
  android:id="@+id/coordinator_layout"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

ref: https://stackoverflow.com/a/39898595/843860

CHAN
  • 1,518
  • 18
  • 16
4

Answer of @Ansh does not resolved my similar case, but only setting IDs to the CoordinatorLayout and also AppBarLayout did it! This way, state of CollapsingToolbarLayout will be saved automatically.

YUSMLE
  • 705
  • 6
  • 21