“Hello, Jetpack” : Build your first Jetpack application

This document walks you through the basic process of building a simple JetPack-based application.

Set up your application

Perform the following steps to set up the application to use Jetpack:

  1. Launch Android Studio 3.2 or later and, as always, enter information in Create Android Project and Locate Android Device.

    If you are writing applications in Kotlin, check the Include Kotlin support box on the Create Android Project screen.

  2. After the “Create Android Project” screen, on the Add An Activity to Mobile page you will be provided with various templates to start your project. We select the Activity & Fragment + ViewModel template and click Next. As shown in the figure:

  3. On the **Configure Activity ** page, fill in the corresponding Name and click Finish, as shown:

Open our Java project folder, as shown in figure, the project includes three categories: initial MainActivity, MainFragment and MainViewModel

  • MainActivity is the entry point for your application. It is a stub that the Activity uses as a container for fragments that are displayed on the initial screen of the application.

  • MainFragment is the initial stub that you Fragment to use in your application.

  • MainViewModel is the ViewModel initial stub that you use in your application.

Using the Jetpack

With these parts, we are ready to implement the ViewModel object, as shown in the figure

class StartViewModel : ViewModel() { private val _data = MutableLiveData<String>() val data: LiveData<String> get() = _data init { _data.value = "Hello, Jetpack!" }}Copy the code

If your application contains multiple pages, you can add a Navigation class to implement Navigation triggers for fragments. The following code is an example of implementing a navigation trigger:

    // Set up a click listener on the login buttonview? .findViewById<Button>(R.id.navigate_bt)? .setOnClickListener {// Navigate to the login destinationview? .let { Navigation.findNavController(it).navigate(R.id.end_action) }Copy the code

If your application requires local access to SQLite data, you can also add the Room persistence library. If your application needs to display large amounts of data on a single screen, you should consider using paging libraries.

Configure the Gradle file

To use Jetpack, you must add the appropriate code to the Gradle file. Because this application uses ViewModel, LiveData, and NavigationController, its Gradle file contains the following code:

       // LiveData + ViewModel

       implementation "android.arch.lifecycle:extensions:$rootProject.archLifecycleVersion"

       // Navigation

       implementation 'androidx.navigation:navigation-fragment:' + rootProject.navigationVersion
       implementation 'androidx.navigation:navigation-ui:' + rootProject.navigationVersion
Copy the code