在RecyclerView滚动时平滑隐藏工具栏?

5

目前我有一个 RecyclerView ,它包含一些项目列表。我正在监听 RecyclerView 的 Scroll listener,如果 RecyclerView 在某个点上达到了 500,它应该隐藏工具栏,并且当它超过 500+ 时,它应该保持隐藏。同样地,在达到 <= 450 时,它会显示工具栏。

这是我迄今为止尝试的代码。问题是,

  1. It hides the toolbar but it flashes when it hides or shows at that mentioned point.
  2. How to achieve a smooth toolbar hide?

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
    
    
            }
    
    
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
    
                scrollD = scrollD + dy;
                Log.d("key", "DY is .." + (dy + scrollD));
    
                if (scrollD >= 500) {
                  // code to hide
                }
    
                if (scrollD <= 450) {
    
    
                 // code to show
    
                }
            }
        });
    

你想要淡入淡出效果还是只是滑动展开/收起? - theapache64
2个回答

5

使用CoordinatorLayout替代线性/相对布局,并在工具栏中添加以下属性。

app:layout_scrollFlags="scroll|enterAlways"

CoordinatorLayout通过在用户向下滚动时隐藏它并在用户向上滚动时再次显示来处理工具栏的可见性。

代码:

<?xml version="1.0" encoding="utf-8"?>

<!-- $Id$ -->

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

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

     <android.support.v7.widget.Toolbar
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/tool_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_scrollFlags="scroll|enterAlways"  />

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

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

请参考此链接:https://mzgreen.github.io/2015/06/23/如何在列表滚动时隐藏/显示工具栏(第三部分)/


1
我也在寻找同样的解决方案,后来发现这个方法。对我来说运行得很好。
隐藏工具栏
mToolbar.animate().translationY(-mToolbar.getBottom()).setInterpolator(new AccelerateInterpolator()).start();

显示工具栏:
mToolbar.animate().translationY(mToolbar.getTop()).setInterpolator(new AccelerateInterpolator()).start();

在回收视图的滚动监听器上调用这些行。

现在,由于监听器提供了工具栏的dx和dy值。 因此,在上面的代码行中,您可以写成:mToolbar.getTop() 的代替方式:

int heightDelta += dy;
    bothToolbarLayouts.animate().translationY(-heightDelta).setInterpolator(new AccelerateInterpolator()).start();

你已经完成了!

或者,为了更好地理解,可以关注这个链接


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接