CoordinatorLayout Behavior not working when RecyclerView or NestedScrollView scroll programmatically

38 views Asked by At

I have AppBarLayout and BottomNavigationView that both collapse during scroll.

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".presentation.MainActivity">

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

        <com.google.android.material.appbar.MaterialToolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_scrollFlags="scroll|enterAlways"
            app:menu="@menu/activity_main_menu"
            app:title="@string/home"
            app:subtitle="@string/assets"
            app:titleCentered="true"
            app:subtitleCentered="true"/>

    </com.google.android.material.appbar.AppBarLayout>

    // NestedScrollView or RecyclerView
    <include layout="@layout/content_main" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@+id/bottomNav"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        app:menu="@menu/bottom_navigation_menu"
        app:layout_behavior="com.google.android.material.behavior.HideBottomViewOnScrollBehavior" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Calling smoothScrollToPosition(0) and smoothScrollTo(0, 0) to programmatically scroll RecyclerView and NestedScrollView does not trigger the CoordinatorLayout Behavior for AppBarLayout and BottomNavigationView.

For RecyclerView,we can call startNestedScroll to trigger the coordinate behavior like this.

rv.startNestedScroll(ViewCompat.SCROLL_AXIS_VERTICAL, ViewCompat.TYPE_NON_TOUCH)
rv.smoothScrollToPosition(0)

We trigger it every time back press is called.

if (recyclerView.canScrollUp()) {
    recyclerView.smoothScrollUpWithCoordinator()
} else {
    super.onBackPressed()
}

However there is a subtle bug here as sometimes it does not scroll all the way up, if you just slightly scroll the list and the AppBarLayout and BottomNavigationView collapse, calling the above code will scroll only up to most second item based on my checking.

For NestedScrollView startNestedScroll does not work at all.

I don't like the idea of manually expanding AppBarLayout and BottomNavigationView. How to scroll programmatically where it will trigger views' CoordinatorLayout Behavior?

Screen record 1 Screen record 2

0

There are 0 answers