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

Creating the Exploring Layouts project

One of the toughest things in Android is not just finding out how to do something, but finding out how to do something amongst other things. That is why, throughout this book, as well as showing you how to do some neat stuff, we will link lots of topics together into apps that span multiple topics and often chapters. The Exploring Layouts project is the first app of this type. We will learn how to build multiple types of layout while linking them all together in one handy app:

  1. Create a new project in Android Studio. If you already have a project open, select File | New Project. When prompted, choose Open in same window, as we do not need to refer to our previous project.

    Tip

    If you are on the start screen of Android Studio, you can create a new project simply by clicking the Start a new Android Studio project option.

  2. Select the Empty Activity project template, as we will build most of the UI from scratch. Click the Next button.
  3. Enter Exploring Layouts for the name of the project.
  4. All the rest of the settings are the same as we have used for the previous three projects.
  5. Click the Finish button.

Look at the MainActivity.kt file. Here is the entirety of the code, excluding the import… statements:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}

Locate the call to setContentView and delete the entire line. The line is shown highlighted in the previous code.

This is just what we want, because now we can build our very own layouts, explore the underlying XML, and write our own Kotlin code to display these layouts. If you run the app now, you will just get a blank screen with a title; not even a Hello World! message.

The first type of layout we will explore is the LinearLayout.