[英]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.