fbpx

Guessing Game – ViewModel

Reading Time: 4 minutes

In this chapter of the Guessing Game tutorial we are going to implement the first ViewModel, which will be a helper to change in real time the username.

In the very last chapter we have implemented the Navigation Component. This Jetpack library is responsible for the navigation inside of the app.

In our case, we have implemented 2 destinations. The first is the GameFragment, the second is the bottom sheet dialog. We can open it by tapping on the TextView of the username, or by clicking on the pen icon. After that, we can write our username inside of the EditText, but still it won’t be changed in the app.

We are going to implement this functionality by using a ViewModel and a LiveData. This LiveData will hold the username, what we will bind to the TextView inside of the GameFragment using Data Binding with layout variables and layout expressions.

So, let’s start coding. 😎

GitHub

If you haven’t done the previous chapters, then from GitHub you can download the starter project for this chapter.

GitHub – navigation_component branch

Step 1 – Create new package

The first step in this chapter will be the creation of a new package. After that, we are going to have inside of this package the ViewModels.

So, click with the right mouse button on the package of ui. From the quick menu select New -> Package.  Then, in the popup window name the package as

“com.inspirecoding.guessinggame.viewmodel”

Be careful! Don’t forget to replace the ui word with viewmodel.

If you are done, then click on the OK button.

Step 2 – Create the ViewModel class

Next, click on the viewmodel package with the right mouse button, and from the quick menu select New -> Kotlin File/Class. In the popup window name the new file as “PlayerViewModel”.

After the creation extend the class by ViewModel().

We will have only one LiveData inside of the PlayerViewModel. This LiveData will contain the current username.

We are going to create first a private MutableLiveData and a LiveData will get back its value. To set the username, we gonna create a separate function. Inside of this function we will set the value of the MutableLiveData.


set and get back the username
LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

It means, if we set the value of the LiveData, then the UI will be notified about the changes. In our case, we will observe the LiveData  directly inside of the layout file using Data Binding.

Step 3 – Layout variables

To start observing the username LiveData from the XML layout, we have to create a layout variable for the PlayerViewModel.

So, open the fragment_game.xml file from the res->layout folders. In the preparation chapter, we have transformed the layout to a Data Binding layout. It means, the root view is inside of a <layout> tag and at the beginning of the layout, there is the <data> tag also.

The layout variable has to be defined inside of this <data> tag. So, copy and paste the below lines into this tag.


playerViewModel

Step 4 – Layout expression

Next, we will implement the last step of the observation using layout expression. Layout expressions are placed in the value of element attributes and they use the @{expression} format.

So, we are going to use layout expression to set the text attribute of the tv_player TextView, which looks like below.

android:text=“@{playerViewModel.username}”

Copy and paste this line into the tv_player TextView.

Add the ViewModel to GameFragment

Before we can start using the ViewModel inside of the XML layout, we have to initialize the above defined PlayerViewModel class inside of the GameFragment class also.

So, open the GameFragment from the ui package and paste the below line before the onCreate() method.


playerViewModel 

Check out this line. Here, we used the Navigation Component to get an instance of the PlayerViewModel::class.

Thenafter, paste the below line into the onCreate() method, before the return statement but after the initialization of the binding.

binding.playerViewModel = playerViewModel

Run the app

It’s time to test the new features. If you run now the app, then you should see the “Enter your name!” text in place of the username.

Step 5 – Set the username

In the next step, we are going to implement, how we can change the username. We are going to use the setPlayersName() method, what we have implemented in the PlayerViewModel class.

We are going to use again Data Binding to bind this method to the XML layout using a layout expression.

So, open the fragment_change_player_dialog.xml file from the res->layout folders. Then, paste the below code also into the <data> tag.


playerViewModel

We are going to use the onTextChanged() method of the EditText. Without Data Binding we would do it inside of the ChangePlayerDialogFragment class.

In our case, the new way, what we are going to use, is much safer because it’s checked at compile time and uses a lambda expression to call the setPlayersName() method of the view model.

So, copy and paste the below line into the til_name EditText.


android:onTextChanged

This line means, when we are typing something in the EditText, then it will notify the LiveData, and the username in the GameFragment gonna be changed, because of the observer.

Add the ViewModel to ChangePlayerDialogFragment

As before, we have to add the PlayerViewModel to the Data Binding’s playerViewModel also.

So, open the PlayerViewModel  class from the viewmodel package and paste before the onCreate() method the below line.


playerViewModel 

Then, paste the below line into the onCreate() method, before the return statement and after the initialization of the binding.

binding.playerViewModel = playerViewModel

Run the app

Run again the app. Now, if you start typing a new username in the bottom sheet dialog, then the username in the game should be changed.

GitHub

The source code is available on GitHub

GitHub – viewmodel branch

Questions

I hope the description was understandable and clear. But, if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂

 


 

Click to rate this post!
[Total: 0 Average: 0]
Follow and like us:

Leave a comment

stay informed!

Subscribe to receive exclusive content and notifications