How to setup Jetpack Compose to a new or existing Android project
This tutorial covers how to create a new Jetpack Compose Android project and how to add Jetpack Compose to an existing project. This tutorial uses Android Studio Bumblebee on MacOS 12.3 but the steps should be similar to all latest version of the IDE and Operating Systems.
Create a new Jetpack Compose project using Android Studio
From the 'Welcome to Android Studio' wizard, click on the 'New Project' button on the top right.
or if you already have an Android Studio project open, go to:
File → New → New Project...
In the 'New Project' wizard select the Empty Compose Activity and press Next.
Give a name to your project, a package name and specify where to save the project.
your project is now setup and ready to run.
Hit the ▶️ Run Button or press ^R
on Mac (CTRL + R
on Windows) to run your new Jetpack Compose app.
Add Jetpack Compose to your existing project
The minimum SDK for Jetpack Compose is 21.
Go to your application's build.gradle
file (usually app/build.gradle
) and include Compose in your buildFeatures
:
android {
buildFeatures {
compose true
}
composeOptions {
kotlinCompilerExtensionVersion '1.2.0'
}
}
next, include the different Jetpack Compose dependencies in your dependencies
block:
dependencies {
implementation 'androidx.activity:activity-compose:1.3.1'
implementation "androidx.compose.animation:animation:1.1.1"
implementation "androidx.compose.foundation:foundation:1.1.1"
implementation "androidx.compose.material:material:1.1.1"
implementation "androidx.compose.runtime:runtime:1.1.1"
implementation "androidx.compose.ui:ui:1.1.1"
}
How to use Jetpack Compose in your Activity
Make your Activity
extend ComponentActivity
(part of the activity-compose artifact).
The regular setContentView()
function call is replaced with setContent {}
which is the entry point to Compose:
class MyActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
// use your composables here
}
}
}
How to use Jetpack Compose in your Fragment
In your Fragment
's onCreateView()
return a ComposeView()
instead of inflating a view:
class MyFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater?,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setViewCompositionStrategy(DisposeOnViewTreeLifecycleDestroyed)
setContent {
// use your composables here
}
}
}
}
Congratulations! You have now setup Jetpack Compose to your project. 👏
Related Resources
- Jetpack Compose basics: a short video demonstrating the basics layouts and components of Jetpack Compose.
- How to understand Jetpack Compose code: a blog post teaching you how to read Jetpack Compose code coming from Android Views.
- Jetpack Compose Version: a website that displays the latest version of all Jetpack Compose dependencies.