[英]Hiding Toolbar smoothly on RecyclerView Scroll?
目前我有一个包含一些项目列表的RecyclerView
。 我正在听RecyclerView的Scroll listener
,如果RecyclerView在某些时候说500,它应该隐藏工具栏,当它超过500+时它应该保持隐藏状态。 同样,当我达到<= 450时,它会显示工具栏。
这是我到目前为止尝试过的代码。 问题是,
如何实现平滑的工具栏隐藏?
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 } } });
使用CoordinatorLayout而不是Linear / Relative布局,并将以下属性添加到工具栏。
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/How-to-hideshow-Toolbar-when-list-is-scrolling(part3)/
我也在寻找相同的解决方案并找到了这个。 和我一起工作。
隐藏工具栏
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();
瞧,你做完了!
或者更好地理解它,请点击此链接
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.