Introduction

Dialogs are a great addition to our applications. When we want to show some quick information to the users or get their confirmation on some actions, dialogs are the way to go for it.

When adopting the MVVM pattern with Jetpack Navigation, we might not be so clear on how to display those Dialogs to the users, and here’s this guide to using DialogFragments in MVVM architecture.

Implementation

Let’s quickly go over the implementation steps to display DialogFragments to our users. Note that this is not a guide on how to get started in MVVM from basics and loading DialogFragments.

In this guide, we will follow with an example of getting the ‘UPI ID’ of a user using a dialogFragment.

Step 1

We will create the layout file for the dialog – ‘dialog_upi.xml‘ –

Step 2

We make use of the ViewModel which listens to the button clicks and sets the value to the SingleLiveEvent.

Step 3

Let’s define the view layer. We will extend our fragment class to DialogFragment.

Here, we use the auto-generated binding class to inflate our XML layout. In the onResume, we set the width and height of our dialog according to the screen size. We observe the isSubmitAction SingleLiveEvent which gets its value from the onClick event of the cancel and okay buttons. This in turn sets the value of canSaveData SingleLiveEvent which is observed in the calling fragment. Another thing to note here is that we use requireActivity() ViewModelStoreOwner to instantiate our VM.

Step 4

In our calling fragment, we instantiate the UPIViewModel with the same requireActivity() owner so that it can listen to the canSaveData SingleLiveEvent and fetch the data. This is the concept of using SharedViewModel.

Step 5

In our navigation graph, we will define the dialog and define an action from the callingFragment to the dialogFragment.

Then we will call the navigate() method of the NavController class and pass the actionID.

Conclusion

In my case, I wanted to display a dialog popping up from the bottom of the screen and so I extended my fragment class to BottomDialogFragment and done! It is this simple to display a dialog to the user and get the input easily following the MVVM architecture.

Leave a Reply

Your email address will not be published. Required fields are marked *