Currently I've a RecyclerView
that holds some list of items. I'm listening the Scroll listener
of RecyclerView and if the RecyclerView at some point say 500, it should hide the toolbar and it should remain hide when it crosses to 500+. Similarly, it shows the toolbar when i reaches <= 450.
This is the code I've tried so far. The problem is,
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
}
}
});
Use CoordinatorLayout instead of Linear/Relative layout and add the following attribute to the toolbar.
app:layout_scrollFlags="scroll|enterAlways"
CoordinatorLayout handles visibility of toolbar by hiding it when the user scrolls down and showing it again when the user scrolls up.
Code:
<?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>
Refer this link : https://mzgreen.github.io/2015/06/23/How-to-hideshow-Toolbar-when-list-is-scrolling(part3)/