Implementing Modal Bottom Sheet in Fragment
It is an undisputed fact that a Sheet in android is modernly used in place of a Dialog. Its simplicity and amazing design gives it a head start. In Material Design, Sheets are explicitly categorised for different usages.
I will be more focused on Modal Bottom Sheet which
renders a shadow on the content below it to indicate that it is a modal, essentially a dialog. If the content outside of the dialog is tapped then the bottom sheet is dismissed. Modal bottom sheets can be dragged vertically and dismissed by completely sliding them down.
However, in this article, we will take a look at how a modal bottom sheet is being implemented in a fragment.
Scope
A Football Fixtures app was developed and will be used as a sample project. Few of the libraries used in this project include Databinding, Dagger 2, Retrofit, Glide, etc.
Please note that some parts of the code will be extracted and will not be different.
Project Configuration
Add the appcompat
and support design
libraries to your project
Getting Started
From the demo shown above, we could see that the modal bottom sheet is shown upon a click on a club team list item. Hence, we have the following views:
- Modal bottom sheet
- TextView: to display the club name
- ImageView: to display the close button and club logo
- RecyclerView: to display the selected team/club players list
Creating Layouts
We have two different layout files: team_line_names.xml
and fragment_bottom_sheet.xml
.
Fragment file
behavior_peekHeight
defines the initial height of the modal bottom sheet.
Players list
Dynamic Sections
In this section, we are going to fetch and display the players and their respective roles from the Football Data API endpoint. The architecture used is MVVM. So, the data fetch is done in the repository and passed through the ViewModel to the views.
For quicker grasp,
- The data is fetched in the
Repository.kt
- Returned data is passed via the
TeamViewModel.kt
- Accessed in the
TeamFragment.kt
- In order to display the data in the modal bottom sheet fragment, the data from the fragment class is passed to the
CompetitionDetailsActivity.kt
through a callback. - Then, the modal bottom sheet fragment is called by the activity to display the received data.
TeamFragment.kt class
CompetitionDetailsActivity.kt class
The sendTeam
method returns an object of PlayerResponse
. A check is made whether a modal is opened or not to avoid calling multiple instances of the bottom sheet.
BottomSheetFragment.kt class
The updateContent
method checks if the current activity that called the fragment is actually available to avoid app crash.
Then, the data is passed through the initRecyclerView
method to the BottomSheetAdapter
class to bind the data to the view.
BottomSheetAdapter.kt class
References
Happy coding! :)