Creating a New Class

In the project tool window, right-click the com.bignerdranch.android.geoquiz package and select NewKotlin File/Class. Enter Question for the name. Select Class from the Kind dropdown. Click OK (Figure 2.2).

Figure 2.2  Creating the Question class

Creating the Question class

Android Studio will create and open a file called Question.kt. In this file, add two member variables and a constructor.

Listing 2.1  Adding to Question class (Question.kt)

class Question {
}
data class Question(@StringRes val textResId: Int, val answer: Boolean)

The Question class holds two pieces of data: the question text and the question answer (true or false).

The @StringRes annotation is not required, but we recommend you include it for two reasons. First, the annotation helps the code inspector built into Android Studio (named Lint) verify at compile time that usages of the constructor provide a valid string resource ID. This prevents runtime crashes where the constructor is used with an invalid resource ID (such as an ID that points to some resource other than a string). Second, the annotation makes your code more readable for other developers.

Why is textResId an Int and not a String? The textResId variable will hold the resource ID (always an Int) of the string resource for a question.

We use the data keyword for all model classes in this book. Doing so clearly indicates that the class is meant to hold data. Also, the compiler does extra work for data classes that makes your life easier, such as automatically defining useful functions like equals(), hashCode(), and a nicely formatted toString().

Your Question class is now complete. In a moment, you will modify MainActivity to work with Question. First, let’s take a look at how the pieces of GeoQuiz will work together.

You are going to have MainActivity create a list of Question objects. It will then interact with the TextView and the three Buttons to display questions and provide feedback. Figure 2.3 diagrams these relationships.

Figure 2.3  Object diagram for GeoQuiz

Object diagram for GeoQuiz
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.183.172