【问题标题】:How to override CoordinatorLayout.Behavior without breaking CoordinatorLayout.LayoutParams如何在不破坏 CoordinatorLayout.LayoutParams 的情况下覆盖 CoordinatorLayout.Behavior
【发布时间】:2019-04-05 21:36:19
【问题描述】:

我正在创建一个 Android 应用程序,并且我想隐藏 BottomAppBar(它有一个锚定在中心的工厂)每当我滚动我的活动片段内的 RecyclerView 而不更改 @ 的布局时987654325@.

按照一些在线指南,我创建了自己的类,该类扩展 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)));
    }
}

没有自定义类,这是(期望的)结果(但滚动隐藏行为显然不起作用)

使用自定义类,这是(不需要的)结果(但滚动隐藏行为确实有效)

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

【问题讨论】:

    标签: java android android-coordinatorlayout android-bottomappbar


    【解决方案1】:

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

    最好的办法是让您的自定义行为扩展它而不是空的 CoordinatorLayout.Behavior(或至少复制相关代码以绘制切口)并从那里开始。

    顺便问一下,app:hideOnScroll (related question) 不适合你吗?

    【讨论】:

    • 当然我忘了添加app:hideOnScroll ...但是由于某种原因,按照您的建议扩展CoordinatorLayout.Behavior 不起作用。感谢您的精彩回答!
    猜你喜欢
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 2010-12-21
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 2010-11-04
    相关资源
    最近更新 更多