Reader small image

You're reading from  Android Programming with Kotlin for Beginners

Product typeBook
Published inApr 2019
Reading LevelIntermediate
PublisherPackt
ISBN-139781789615401
Edition1st Edition
Languages
Right arrow
Author (1)
John Horton
John Horton
author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton

Right arrow

Chapter 24. Design Patterns, Multiple Layouts, and Fragments

We have come a long way since the start, when we were just setting up Android Studio. Back then, we went through everything step by step, but as we have proceeded, we have tried to show you not just how to add x to y or feature A to app B, but to enable you to use what you have learned in your own way in order to bring your own ideas to life.

This chapter is more focused on your future apps than any other chapter in this book has been so far. We will look at a few features of Kotlin and Android that you can use as a framework or template to make even more exciting and complex apps while keeping the code manageable. Furthermore, I will suggest areas of further study that are barely touched on in this book, given its limited scope.

In this chapter, we will learn about the following:

  • Patterns and the model-view-controller

  • Android design guidelines

  • Getting started with real-world designs and handling multiple different devices

  • An introduction...

Introducing the model-view-controller pattern


The phrases model, view, and controller reflect the separation of the different parts of our app into distinct sections, called layers. Android apps commonly use the model-view-controller pattern. A pattern is simply a recognized way to structure code and other application resources, such as layout files, images, and databases.

Patterns are useful to us because, by conforming to a pattern, we can be more confident that we are doing things right, and will be less likely to have to undo lots of hard work because we have coded ourselves into an awkward situation.

There are many patterns in computer science, but just an understanding of the MVC pattern will be enough to create some professionally built Android apps.

We have been partly using MVC already, so let's look at each of the three layers in turn.

Model

The model refers to the data that drives our app and any logic/code that specifically manages it and makes it available to the other layers....

Android design guidelines


App design is a vast topic – so vast that it could only begin to be taught in a book dedicated solely to the topic. Also, like programming, you can only start to get good at app design with constant practice, review, and improvement.

So, what exactly do I mean by design? I am talking about where you put the widgets on the screen, which widgets, what color they should be, how big they should be, how to transition between screens, the best way to scroll a page, when and which animation interpolators to use, what screens your app should be divided into, and much more besides this.

This book will hopefully leave you well-qualified to be able to implement all your chosen answers to these questions and many more besides. Unfortunately, it does not have the space, and the author probably doesn't have the skill to teach you how to make those choices.

Note

You might be wondering, "What should I do?". Keep making apps and don't let a lack of design experience and knowledge stop...

Real-world apps


So far, we have built a dozen or more apps of various complexity. Most were designed and tested on a phone.

Of course, in the real world, our apps need to work well on any device, and must be able to handle what happens when in either portrait or landscape view (on all devices).

Furthermore, it is often not enough for our apps to just work and look "OK" on different devices. Often, our apps will need to behave differently and appear with a significantly different UI based on whether the device is a phone, a tablet, or has landscape/portrait orientation.

Note

Android supports apps for large screen TVs, smart watches via the wear API, virtual and augmented reality, and "things" for the internet of things. We will not be covering the latter two aspects in this book, but by the end of it, it is the author's hope that you will be sufficiently prepared to venture into these topics should you choose to.

Look at the following screenshot of the BBC News app running on an Android phone...

Device detection mini app


The best way to learn about detecting and responding to devices and their varying attributes (screens, orientations, and so on) is to make a simple app. Let's do this by going through the following steps:

  1. Create a new Empty Activity project and call it Device Detection. Leave all the other settings as their defaults.

  2. Open the activity_main.xml file in the Design tab and delete the default Hello world! TextView.

  3. Drag a Button to the top of the screen and set its onClick property to detectDevice. We will code this function in a minute.

  4. Drag two TextView widgets onto the layout, one below the other, and set their id properties to txtOrientation and txtResolution, respectively.

  5. Check that you have a layout that looks something like the following screenshot:

    Note

    I have stretched my widgets (mainly horizontally) and increased the textSize attributes to 24sp to make them clearer on the screen, but this is not required for the app to work correctly.

  6. Click the Infer Constraints...

Configuration qualifiers


We have already seen configuration qualifiers, such as layout-large or layout-xhdpi, in Chapter 3 , Exploring Android Studio and the Project Structure. Here, we will refresh and expand our understanding of them.

We can begin by alleviating our reliance on the controller layer to influence app layout by using configuration qualifiers. There are configuration qualifiers for size, orientation, and pixel density. To take advantage of a configuration qualifier, we simply design a layout in the usual way, optimized for our preferred configuration, and then place that layout in a folder with a name that Android recognizes as being for that particular configuration.

For example, in the previous app, putting a layout in the land folder tells Android to use that layout when the device is in landscape orientation.

It is likely that the preceding statement seems slightly ambiguous. This is because the Android Studio project explorer window shows us a file and folder structure...

Fragments


Fragments will likely become a staple of almost every app you make. They are so useful, there are so many reasons to use them, and—once you get used to them—they are so simple, that there is almost no reason not to use them.

Fragments are reusable elements of an app, just like any class, but, as we mentioned previously, they have special features—such as the ability to load their own view/layout, as well as their very own lifecycle functions—which make them perfect for achieving the goals we discussed in the Real-world apps section.

Let's dig a bit deeper into fragments, one feature at a time.

Fragments have a life cycle too

We can set up and control fragments, very much like we do with activities, by overriding the appropriate lifecycle functions.

The onCreate function

In the onCreate function, we can initialize variables and do almost all the things we typically do in the Activity onCreate function. The big exception to this is initializing our UI.

The onCreateView function

In the...

Our first fragment app


Let's build a fragment in its simplest possible form so that we can understand what is going on, before we start producing Fragment objects all over the place that are of genuine use.

Note

I urge all readers to go through and build this project. There is a lot of jumping around from file to file, and just reading the instructions alone can make it seem more complex than it really is. Certainly, you can copy and paste the code from the download bundle, but please also follow the steps, and create your own projects and classes. Fragments are not too tough, but their implementation, like their name suggests, is a little fragmented.

Create a new project called Simple Fragment using the Empty Activity template and leave the rest of the settings at their defaults.

Note that there is the option to create a project with a fragment, but we will learn more by doing things ourselves from scratch.

Switch to activity_main.xml and delete the default Hello world! TextView.

Now, make...

Fragment reality check


So, what does this fragment stuff really do for us? Our first fragment mini-app would have the same appearance and functionality had we not bothered with the fragment at all.

In fact, using the fragment has made the whole thing more complicated! Why would we want to do this?

We kind of know the answer to this already; it just isn't especially clear based on what we have seen so far. We know that a fragment, or fragments, can be added to the layout of an activity.

We know that a fragment not only contains its own layout (view), but also its very own code (controller), which, although hosted by an activity, is virtually independent.

Our quick app only showed one fragment in action, but we could have an activity that hosts two or more fragments. We then effectively have two almost independent controllers displayed on a single screen. This sounds like it could be useful.

What is most useful about this, however, is that when the activity starts, we can detect attributes of...

Frequently asked question


Q) If we simply have an ArrayList, as we did with the Note to self app, where will it go? How would we share it between fragments (assuming both/all fragments need access to the same data)?

A) There is an entirely more elegant solution we can use to create a model layer (both the data itself and the code to maintain the data). We will see this when we explore NavigationDrawer in Chapter 26, Advanced UI with Navigation Drawer and Fragments, and Android databases in Chapter 27, Android Databases.

Summary


Now that we have a broad understanding of what fragments are meant for and how we can begin to use them, we can start to go deeper into how they are used. In the next chapter, we will make a couple of apps that use multiple fragments in different ways.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Programming with Kotlin for Beginners
Published in: Apr 2019Publisher: PacktISBN-13: 9781789615401
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Author (1)

author image
John Horton

John Horton is a programming and gaming enthusiast based in the UK. He has a passion for writing apps, games, books, and blog articles. He is the founder of Game Code School.
Read more about John Horton