Android Programming with Kotlin for Beginners
上QQ阅读APP看书,第一时间看更新

Exploring the project's Kotlin code and the main layout's XML code

We are going to look at the resource files containing the code that defines our simple UI layout and the file that has our Kotlin code. At this stage, we won't try to understand it all, as we need to learn some more basics before it makes sense to do so. What we will see, however, is the basic content and structure of both files, so we can reconcile their content with what we already know about Android resources and Kotlin.

Examining the MainActivity.kt file

Let's take a look at the Kotlin code first. You can see this code by left-clicking on the MainActivity.kt tab, as shown in the following screenshot:

As we are not looking at the intricate details of the code, an annotated screenshot is more useful than reproducing the actual code in text form. Regularly refer to the following screenshot while reading this section:

The first thing to note is that I have added a few empty lines in among the code to space things out and present a clearer image.

Code folding (hiding) in Android Studio

Now, look at the left-hand side of the window in Android Studio (not the preceding screenshot) and observe all the + and - buttons on the left-hand side of the editor that can collapse and expand parts of the code:

I have collapsed some parts of the code, and have left other parts visible. So, what you can see on your screen is slightly different to what you will see if you look at the preceding screenshot. In Android Studio, play with the + and buttons for a while to practice hiding and unhiding sections of the code. You might be able to get your screen to look like the preceding screenshot, but this is not a requirement to continue. The technical term for hiding code like this is called folding .

The package declaration

Part 1 is called the package declaration and, as you can see, it is the package name that we chose when we created the project, preceded by the word package. Every Kotlin file will have a package declaration at the top.

Importing classes

Part 2 is six lines of code that all begin with import. After import, we can see there are various dot-separated words. The last word of each line is the name of the class that line imports into our project, and all the earlier words in each line are the packages and subpackages that contain these classes.

For example, this next line imports the AppCompatActivity class from the androidx.appcompat.app package and subpackages:

import androidx.appcompat.app.AppCompatActivity

This means that in our project, we will have access to these classes. In fact, it is these classes that the autogenerated code uses to make our simple app, which we saw in action in the previous chapter.

We will not discuss all of these classes in this chapter. It is just the idea that we can do this importing of classes that gives us access to more functionality that is significant right now. Note that we can add extra classes from any package at any time, and we will do so when we improve upon our app shortly.

The class declaration

Part 3 of our code is called the class declaration. Here is that line in full; I have highlighted one part of it, as follows:

class MainActivity : AppCompatActivity() {

The class declaration is the start of a class. Notice that the highlighted part, MainActivity, is the name that was autogenerated when we created the project and is also the same as the MainActivity.kt filename. This is as we would expect, having discussed Kotlin classes previously.

The colon (:) means that our class called MainActivity will be of the type AppCompatActivity. This indicates that although there are not that many lines of code in this file, we are also using more code that we don't see that comes from the AppCompatActivity class. All this and more will become clear in Chapter 10, Object-Oriented Programming.

Finally, for part 3, look at the opening curly brace at the end of the line: {. Now look at the bottom of the screenshot at part 4 of our code. This closing curly brace (}) denotes the end of the class. Everything in between the opening and closing curly braces, {...}, is part of the class.

Functions inside the class

Now look at part 5 of the code. Here is that line of code in full, with the key part for our current discussion highlighted:

override fun onCreate(savedInstanceState: Bundle?) {

This is a function signature. The highlighted part, onCreate, is the function name. The Kotlin fun keyword makes it clear that this is the start of a function. We make a function execute its code by using its name. We say we are calling a function when we do this.

Although we will not concern ourselves now with the parts of the code on either side of the function name, you might have noticed Bundle, one of the classes that we imported in part 2 of our code. If we remove that related import line, Android Studio will not know what the Bundle class is, and it will be unusable and highlighted in red underline as an error.

Our code will then not compile and run. Notice that the very last thing in the line of the preceding code is an opening curly brace ({). This denotes the start of the code contained within the onCreate function. Now jump to part 6 of our code and you will see a closing curly brace (}). You might have guessed that this is the end of the function. Everything in between the opening and closing curly braces of the onCreate function is the code that executes when the function is called.

We do not need to go into what this code does yet but, as an overview, it sets up the appearance and layout of the app by referring to some resource files that were autogenerated by Android Studio when we created the project. I have highlighted these resource files with an outline in the previous screenshot labeled 9.

Parts 7 and 8 are also functions that I have collapsed to make the screenshot and this discussion more straightforward. Their names are onCreateOptionsMenu and onOptionsItemSelected.

We know enough about our Kotlin code to make some progress. We will see this code again and change it later in this chapter.

A summary of the Kotlin code so far

It is true that, contained within the preceding code, there is some complex syntax. However, what we are doing is building up just enough knowledge about this code, so that we can work within it and begin to make rapid progress in learning Kotlin and Android without having to read hundreds of pages of Kotlin theory first. By the end of the book, all the code will make sense. But in order to make quick progress now, we just need to accept that some of the details will remain a mystery for a little while longer.

Examining the main layout file

Now we will look at just one of the many .xml files. There are several different layout files and we will meet them all throughout the course of this book, but let's start with the most significant one that decides the appearance of our app.

Left-click on the content_main.xml tab next to the MainActivity.kt tab that we have been discussing.

In the main window on the right-hand side, you will see the Design view of our app, as shown in the following screenshot:

Most of the work that we do throughout the book when we design apps will be done in this design view. It is important, however, to know what is going on behind the scenes.

The design view is a graphical representation of the XML code contained in the content_main.xml file. Click on the Text tab (as outlined near the bottom-left in the previous screenshot) to see the XML code that forms the layout. I have annotated a screenshot of the XML text so that we can discuss it next:

The first thing to note is that this file does not represent the entire layout. It does, however, represent most of the surface area and the Hello World message in the center. Also, on the left-hand side, we can see the now familiar + and icons so that we can fold and unfold sections of the code.

UI layout elements

If we first look at the part of the code labeled 1, we can see that the very first thing is …ConstraintLayout.... A ConstraintLayout element is a UI element that is used to wrap other parts of the UI.

Note

There are more technical and specific ways to refer to the different "elements" of our user interface designs. As we progress, we will introduce terminology such as widget, view, and view-group, as well.

When we add a new element to a UI in Android, we always start a line with a left angle bracket (<) followed by the element's name.

The code that follows this rather long and cumbersome-looking line defines the attributes that this element will have. This can include dozens of different things, depending upon the type of UI element it is. Here, among a bit of other XML, we can see things such as layout_width, layout_height, and showIn. All these attributes define how the ConstraintLayout element will appear on the user's screen. The attributes for the ConstraintLayout element end at the first right angle bracket (>), labeled 1b.

If we look at the bottom of our XML screenshot, we will see the code labeled 2. This code, </…ConstraintLayout>, marks the end of the ConstraintLayout element Anything in between the closing right angle bracket (>) of the element's attributes and the </…ConstraintLayout> code that defines its end is considered a child of the element. So, we can see that our ConstraintLayout element has (or contains) a child. Let's take a look at that child now.

UI text elements

Using what we have just learned, we can devise that the UI element that starts at position 3 in the screenshot is called a TextView element. Just like its parent, it starts with a left angle bracket (<) and its name: <TextView.... If we look further into our TextView element, we can see that it has several attributes. It has a text attribute that is set to "Hello world!". This, of course, is the exact text that our app shows to the user. It also has layout_width and layout_height attributes that are both set to "wrap_content". This tells the TextView element that it can take up as much space as the content it has needs, but no more. As we will see throughout the book, there are many more attributes available for this and other UI elements.

Notice that the code at the 4 position on our XML screenshot is />. This marks the end of the TextView element. This is slightly different to how the end of the ConstraintLayout element was written. When an element in XML has no children, we can just end it like this: />. When the element has children and its end comes further on in the code from where its attributes are defined, it is much clearer to end the element by repeating its name like this: </…ConstraintLayout>.

Note

You might be wondering why the element name for the TextView element is short and concise (simply, TextView), yet the full name for the ConstraintView element is preceded by apparent complicated clutter (androidx.constraintlayout.widget.ConstraintLayout). This ConstraintLayout element is a special version of the layout that is used to ensure our app's compatibility with older versions of Android. As we will see in a minute, when we add buttons to the app, most elements have simple and concise names.

We will edit this code in the next section and learn more about the attributes, as well as explore another type of UI element – that is, a Button element.