如何在不破坏 CoordinatorLayout.LayoutParams 的情况下覆盖 CoordinatorLayout.Behavior

How to override CoordinatorLayout.Behavior without breaking CoordinatorLayout.LayoutParams

我正在创建一个 Android 应用程序,每当我滚动片段内的 RecyclerView 时,我想隐藏 BottomAppBar(它有一个锚定在中心的 fab)我的 activity 没有改变 BottomAppBar.

的布局

根据一些在线指南,我创建了自己的 class 扩展 CoordinatorLayout.Behavior 并覆盖 onStartNestedScroll & onNestedPreScroll 以便 BottomAppBar 得到每当我滚动时隐藏。

<android.support.design.widget.CoordinatorLayout ...>
    ...
    <android.support.design.bottomappbar.BottomAppBar
        style="@style/Widget.MaterialComponents.BottomAppBar"
        android:id="@+id/bottom_app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        app:backgroundTint="@color/colorPrimary"
        app:fabAlignmentMode="center"
        app:fabCradleRoundedCornerRadius="15dp"/>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_add_white_24dp"
        app:layout_anchor="@id/bottom_app_bar" />
</android.support.design.widget.CoordinatorLayout>
BottomAppBar bab = (BottomAppBar) findViewById(R.id.bottom_app_bar);
CoordinatorLayout.LayoutParams layoutParams = (CoordinatorLayout.LayoutParams) bab.getLayoutParams();
BottomNavigationBehavior bnb = new BottomNavigationBehavior();
layoutParams.setBehavior(bnb);



class BottomNavigationBehavior<V extends View> extends CoordinatorLayout.Behavior<V>{

    @Override
    public boolean onStartNestedScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View directTargetChild, @NonNull View target, int axes, int type) {
        return axes == ViewCompat.SCROLL_AXIS_VERTICAL;
    }

    @Override
    public void onNestedPreScroll(@NonNull CoordinatorLayout coordinatorLayout, @NonNull V child, @NonNull View target, int dx, int dy, @NonNull int[] consumed, int type) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type);
        child.setTranslationY(Math.max(0f, Math.min(child.getHeight(),child.getTranslationY() + dy)));
    }
}

没有自定义 class,这是(期望的)结果(但 scrolling-hiding 行为显然不起作用)

使用自定义 class,这是(不需要的)结果(但 scrolling-hiding 行为确实有效)

我认为,因为我没有修改 layoutParams 参数,而只是行为,布局应该是相同的,但显然我遗漏了一些东西......
有人知道如何解决这个问题吗?

我只浏览了源代码,但是绘图切口是默认的一部分BottomAppBar.Behavior

你最好的选择是让你的自定义行为扩展它而不是空的CoordinatorLayout.Behavior(或者至少复制相关代码来绘制切口)并从那里开始工作。

顺便问一下,app:hideOnScroll (related question) 对你不起作用吗?