Chapter 13. Data Binding: Building Smart Layouts

image

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:

image

The first screen the user sees is GameFragment, and she interacts with it to play the game. It displays information—such ...

Get Head First Android Development, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.