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

The structure of Android's code

In addition to these resources, it is worth noting that Android has a structure to its code. There are many millions of lines of code that we can take advantage of. This code will obviously need to be organized in a way that makes it easy to find and refer to. It is organized into packages that are specific to Android.

Packages

Whenever we create a new Android app, we will choose a unique name, known as a package. We will see how we do this very soon, in the section titled Our first Android app. Packages are often separated into sub-packages so that they can be grouped together with other similar packages. We can simply think of these as folders and sub-folders, which is almost exactly what they are.

We can think of all the packages that the Android API makes available to us as code from a code library. Some common Android packages that we will use include the following:

  • android.graphics
  • android.database
  • android.view.animation

As you can see, they are arranged and named to make what is in them as obvious as possible.

Tip

If you want to get an idea of the sheer depth and breadth of the Android API, then look at the Android package index at https://developer.android.com/reference/packages

Classes

Earlier, we learned that the reusable code blueprints that we can transform into objects are called classes. Classes are contained in these packages. We will see in our very first app how we can easily import other people's packages, along with specific classes from those packages for use in our projects. A class will usually be contained in its own file with the same name as the class.

Functions

In Kotlin, we further break up our classes into sections that perform the different actions of our class. We call these action-oriented sections functions. It is the functions of the class that we will use to access the functionality provided within all the millions of lines of Android code.

We do not need to read the code. We just need to know which class has what we need, which package it is in, and which function from within the class gives us precisely the result we are after.

We can think of the structure of the code we will write ourselves in the same way, although we will usually have just one package per app.

Of course, because of the object-oriented nature of Kotlin, we will only be using selected parts from this API. Note also that each class has its own distinct data. Typically, if you want access to the data in a class, you need to have an object of that class.

Tip

You do not need to memorize this, as we will constantly be returning to this concept in the book.

By the end of this chapter, we will have imported multiple packages, as well as some classes from them. By the end of Chapter 2, Kotlin, XML, and the UI Designer, we will have even written our very own functions.