You might have seen many applications hiding the FAB on scrolling down and showing back when scrolling up. Hiding the FAB leaves nothing in the way of user and the content, making it an overall better UX.

It is very easy to achieve this kind of functionality. The prerequisites of this tutorial is that you have a basic understanding of Recycler View and FloatingActionButton.

First set up a basic Activity with a Coordinator Layout containing a Recycler View and FloatingActionButton, just as below.

Now reference the RecyclerView and FloatingActionButton in the Activity.

Now comes the main part. We will attach a scroll listener to the recycler view, so whenever the user scrolls the list we will get notified and will toggle the visibility of the FAB accordingly. The scroll listener looks like this.

Lets break down the above code and understand each line.

  • hide() and show() are two methods provided by the FAB to hide/show the FAB button with a smooth animation.
  • dy is a value that changes when you scroll vertically, when the user scrolls down the value is positive and when the user scrolls up the value is negative. So we check if the FAB is visible and the value is positive(i.e. user is scrolling down) we will hide it and if the FAB is hidden and the value is negative(i.e. user is scrolling up) we will show the FAB.

Once you run the app it will look something like this. Simple and slick!

One Response

Leave a Reply

Your email address will not be published.

twenty − twelve =