Bind ViewModel to a Fragment (Pick Players)

Kotlin and Android Development featuring Jetpack — by Michael Fazio (24 / 125)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Create a ViewModel (Pick Players) | TOC | Add AI Spinner to Player List Items 👉

Now it’s time for us to really get into the Data Binding library. So far, we’ve done a bunch of setup (sorry, there’s a bit more coming) and some static binding with isVisible and isChecked, but using dynamic variables is where data binding really shines. The ability to set up complex objects in our code, then bind them to the UI with minimal work is why I’m recommending data binding so emphatically. Working though this next section will set us up for later chapters where we’re displaying data from a database or web services. But first, we need to finish up a few more things to get this all working.

Update PickPlayersFragment to Use PickPlayersViewModel

To use the PickPlayersViewModel we just created, we’re going to need to do a few things:

  1. Add a <variable> called viewModel to fragment_pick_players of type PickPlayersViewModel.
  2. Declare a value of type PickPlayersViewModel via the by activityViewModels() syntax.
  3. Bind that instance to the viewModel variable on FragmentPickPlayersBinding.

Once those steps are complete, we can start using viewModel in our layout file to reference the NewPlayer instances we created…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.