Including the ViewModel Dependency

Before you can write a ViewModel class, you need to include two libraries in your project. The ViewModel class comes from an Android Jetpack library called androidx.lifecycle, one of many libraries that you will use throughout this book. (You will learn more about Jetpack later in this chapter.) You will also include the androidx.activity library, which adds some functionality to your MainActivity.

To include libraries in your project, you add them to the list of dependencies. Like the configuration for View Binding you did back in Chapter 2, your project’s dependencies live in the app/build.gradle file. Under Gradle Scripts in the project tool window, open the build.gradle file labeled Module: GeoQuiz.app so you can add our new dependencies. You should see something like:

    plugins {
      id 'com.android.application'
      id 'kotlin-android'
    }

    android {
        ...
    }

    dependencies {
        implementation 'androidx.core:core-ktx:1.7.0'
        implementation 'androidx.appcompat:appcompat:1.4.1'
        ...
    }

The dependencies section already includes some libraries that your project requires. You might recognize a few of them, such as Espresso or Kotlin. Gradle also allows you to specify new dependencies. When your app is compiled, Gradle will find, download, and include the dependencies for you. All you have to do is specify an exact string incantation, and Gradle will do the rest.

Add the androidx.lifecycle:lifecycle-viewmodel-ktx and androidx.activity:activity-ktx dependencies to your app/build.gradle file, as shown in Listing 4.1. Their exact placement in the dependencies section does not matter, but to keep things tidy it is good to put new dependencies under the last existing implementation dependency.

Listing 4.1  Adding dependencies (app/build.gradle)

dependencies {
    ...
    implementation 'androidx.constraintlayout:constraintlayout:2.1.3'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.4.1'
    implementation 'androidx.activity:activity-ktx:1.4.0'
    ...
}

As it did when you made the change to enable View Binding, Android Studio will prompt you to sync the file. Either click Sync Now in the prompt or select FileSync Project with Gradle Files, and Gradle will take care of the rest.

..................Content has been hidden....................

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