Home » Android » model view controller – Does Android UI development lend itself well to a particiular design pattern?

model view controller – Does Android UI development lend itself well to a particiular design pattern?

Posted by: admin June 15, 2020 Leave a comment

Questions:

Does the Android platform lend itself well to a particular style of UI programming like MVC or MVP? Most of my UI experience is with spaghetti code on a very old embedded device or in GWT with MVP so I do not know where to start.

How to&Answers:

I do not know if the Android lends itself well to a specific design pattern when it comes to UI development per se, you can certainly use a particular pattern if it helps.

When in doubt you can check out the standard User Interface Guidelines and see what the guidelines are for particular interactions.

Answer:

The MVC Pattern is more or less pre build into android.

You have three layers consisting of:

  • The Model Your data classes, Content providers etc. wrapping all your data.
  • The Controllers Treat all your activities as controller classes. Don’t do anything in them that looks like business logic or data persitance. Just react to events from the model or the user and forward them to the correct layer.
  • The View Often the Activities are called the view because there it is the java code that is closest to the views. But in my opinion the view layer in Android is mostly defined in xml. You define your buttons, images, state changes etc in xml and then connect it with your application through your Activities.

There are some simple rules to follow to have a basic separation of this layers.

  • Define as much of your UI in xml only
    instantiate Views yourself if there
    is no other way to achieve something,
    don’t change the graphical state of
    views from code, for example don’t
    change the background of a button if
    the button is deactivated, or the
    color of a font if a button was
    clicked, do all this through stateful
    drawables, and selectors in xml.
  • Don’t do any data saving or logic in
    your activity classes. Call to extra
    model classes for this purpose. This
    will make your activities clean and
    short
  • If you want to change your data think
    about going through a full
    controller changes model -> model
    informs controller about changes
    -> controller changes UI cycle instead of having the controller
    change the model and the UI
    directly because other observers
    of the modes may not be notified.