How to keep offset with dynamically resized appbar?

Viewed 154

I have the typical collapsing toolbar setup as followed:

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

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="192dp">

        <com.google.android.material.appbar.CollapsingToolbarLayout
            android:id="@+id/collapsingtoolbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|exitUntilCollapsed">

            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"/>
        </com.google.android.material.appbar.CollapsingToolbarLayout>
    </com.google.android.material.appbar.AppBarLayout>
    ...
    ...
    ...
</androidx.coordinatorlayout.widget.CoordinatorLayout>

The problem is that in onPreDraw of one textView on this screen, I need to dynamically change the size of the appBar which messes up the appBar's offset when the view is recreated. In onViewCreated I do:

textView.doOnPreDraw {
    appBar.layoutParams = appBar.layoutParams.apply {
        height = requireContext().dip(300)
    }
}

So now when I am (for example) fully collapsed, go to a different fragment and then go back, the appBar's offset is completely messed up and I am in this half-expanded state. Is there any solution to this problem?

0 Answers
Related