Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 20  Data Binding and MVVM


Different Architectures: Why Bother?


Every app you have written so far has used a simple version of MVC. And, so far – if we have done
our job well – every app has made sense to you. So why change? What is the problem?


MVC as written in this book works just fine for small, simple apps. It is easy to add new features and
easy to think about the moving pieces of the app. It creates a solid foundation for development, gets
your app up and running quickly, and works well in the early phases of a project.


The problem arises when your program grows larger than what we show in this book, as all programs
do. Large fragments and activities are difficult to build on top of and difficult to understand. New
features and bug fixes take longer. At some point, those controllers must be broken down into smaller
pieces.


How do you do that? You figure out the different jobs your big controller classes are doing, and you
give each job its own class. Instead of one big class, you have instances of a few classes doing the job
as a team.


How do you determine what those different jobs are, then? The answer to that question is the definition
of your architecture. People use descriptions like “Model-View-Controller” and “Model-View-
Presenter” to describe at a high level the ways they answer this question. But answering this question is
always your responsibility, so your architecture is always uniquely yours.


BeatBox is designed with an MVVM architecture. We are fans of MVVM because it does a great job
of lifting a lot of boring controller code out into the layout file, where you can easily see which parts
of your interface are dynamic. At the same time, it pulls the non-boring dynamic controller code into a
ViewModel class, where it can be more easily tested and verified.


How large each view model should be is always a judgment call. If your view model grows too large,
you can break it down further. Your architecture is yours, not ours.


Creating BeatBox


Time to get started. The first step is to create your BeatBox app. In Android Studio, select File
→ New Project... to create a new project. Call it BeatBox and give it a company domain of
android.bignerdranch.com. Use API 19 for your minimum SDK and start with one Empty Activity
called BeatBoxActivity. Leave the defaults as they are.


You will be using RecyclerView again, so open your project preferences and add the
com.android.support:recyclerview-v7 dependency.


Now, let’s build out the basics of the app. The main screen will show a grid of buttons, each of which
will play a sound. So, you will need two layout files: one for the grid and one for the buttons.


Create your layout file for the RecyclerView first. You will not need res/layout/
activity_beat_box.xml, so go ahead and rename it fragment_beat_box.xml.

Free download pdf