Chapter 13. Data Binding: Building Smart Layouts
Layouts can do more than control your app’s appearance.
All of the layouts you’ve written so far have been told how they should behave by activity or fragment code. But just imagine if the layouts could think for themselves, and make their own decisions. In this chapter, we’ll introduce you to data binding: a way of boosting your layout’s IQ. You’ll find out how to make views get values directly from the view model. You’ll use listener binding to make buttons call their methods. You’ll even discover how one simple line of code lets views respond to live data updates. Soon, your layouts will be more powerful than ever before.
Back to the Guessing Game app
In the previous two chapters, you built a Guessing Game app that lets the user guess which letters are included in a secret word. When the user guesses all the letters or runs out of lives, the game ends.
The app uses two view models—GameViewModel and ResultViewModel—which hold the app’s game logic and data, and maintain its state when the app is rotated. GameViewModel is used by GameFragment, and ResultViewModel is used by ResultFragment:
The first screen the user sees is GameFragment, and she interacts with it to play the game. It displays information—such as the number of ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access