Auto-Hide or Auto-Extend Floating Action Button in RecyclerView in Android
In the article Auto-Hide or Auto-Extend Floating Action Button for NestedScrollView in Android it’s been discussed and demonstrated how to auto-extend or hide the Floating Action Button in the Nested Scroll View. In this article, it’s discussed how to Hide or Extend the Floating Action Button in Android. Look at the following image to get an overview of the discussion.
Create an empty activity project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Add Required Dependency
Include google material design components dependency in the build.gradle file. After adding the dependencies don’t forget to click on the “Sync Now” button present at the top right corner.
Note that while syncing your project you need to be connected to the network and make sure that you are adding the dependency to the app-level Gradle file as shown below.
Steps to Hide or Extend FAB when scrolled in RecyclerView
Step 1: Working with activity_main.xml file
The main layout of the project contains one RecyclerView and one Normal Floating Action Button. To implement the same layout invoke the following code inside the activity_main.xml file.
Before going to the output we need to populate the RecyclerView with the data. So we need to now work with RecyclerView Adapter and a custom view for the RecyclerView.
Step 2: Create a custom view for RecyclerView
The custom view for the RecyclerView contains one simple icon at the left and two TextViews. To implement the same create a file named recycler_data_view.xml inside the layout folder and invoke the following code.
The above custom view produces the following output for each item in the list:
Step 3: Creating Data Class for RecyclerView
Now creating the data for the above custom view by creating a Data Class, using the following code.
Step 4: Creating the RecyclerView Adapter
The following code needs to invoke in a separate class by creating the class named as MyRecyclerAdapter.
Step 5: Working with the MainActivity.kt file
In this class, we have to create some sample data for the RecyclervView in the form of a list and handle the scroll listener for the recycler view when it is scrolled up and down. When it scrolled up we have to hide the FAB and show the FAB when scrolled down. To implement the same invoke the following code inside the MainActivity.kt file (comments are added for better understanding).
For Extended Floating Action Button
Make changes to the activity_main.xml file by invoking the following code.
Make changes inside the MainActivity.kt file by invoking the following code.
Please Login to comment...