Jetpack Compose 101; Setup the Environment
Tags: android, beginners, tutorial, mobile
Published: 2023-02-04 17:57:20

Welcome to the second installment of the Android Development series! In our previous article, a brief overview of the Jetpack framework and Jetpack Compose was provided. In case you missed it, be sure to catch up by reading it [here](https://ethanrodrigo.hashnode.dev/jetpack-compose-a-modern-ui-toolkit).

It's time to get hands-on and set up the environment for Jetpack Compose. So, grab a coffee, fire up your laptop, and let's dive in.

![75 Funny Coffee Memes To Brighten Up Your Day](https://fluentincoffee.b-cdn.net/wp-content/uploads/2022/05/but-first-coffee.png)

_NOTE_: This article series assumes that you have an understanding of native android development fundamentals. This series is here to take your skills to the next level. The main focus in this series is solely on the Jetpack framework and its capabilities.

Setup the Environment
=====================

Open up the Android Studio(you can download it from [here](https://developer.android.com/studio/install)). If this is your first time, you can see something as follows.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674144707298/899a58d6-5134-4c75-9b33-d549abfac2a1.png?auto=compress,format&format=webp)

Now click the box`New Project` on the top left side.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674144822832/671d17f2-fb35-463f-bb4b-ce51925aae8a.png?auto=compress,format&format=webp)

In the following dialog, select `Phone and Tablet`(often it's selected by default), then `Empty Compose Activity` from the right side. Finally, click on `Next` button.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674144831553/084dd843-e3fe-4214-94b0-f39d7d83ef13.png?auto=compress,format&format=webp)

In the next dialog box, give your app a `Name`. I name it as `My First Compose Application`(I know that's too long).

The `Package name` is a unique identifier for your app on a device. Let it be the default. Also, consider changing the `Minimum SDK`, which is the minimum android version that your app can be installed on.

Keep the default values for the other settings.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674145023518/e7a6c050-6673-41ae-a958-5c16e00a2401.png?auto=compress,format&format=webp)

Give it some time to create and initialize an environment for you. Your internet connection speed affects the initialization process as Android Studio downloads some packages from the internet.

Then you'll have something as follows

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674145484670/d58685a4-7037-4663-8796-921b1523cf96.png?auto=compress,format&format=webp)

A quick glimpse at Android Studio
=================================

As mentioned earlier in the post, this series focuses more on the `Jetpack` framework, and assumes you have some experience with android development and Android Studio. The following tools will aid us in our journey of learning Jetpack Compose.

Design View
-----------

On the left side, you will find three panels labeled Code, _Design_, and _Split_. The _Code_ panel displays the code that you are currently working on, the _Design_ panel shows the visual representation of the UI in a composable function, and the _Split_ panel combines both in a single panel.

Click on the _Split_ box and you will see the UI from the function called `Greeting`. If you see nothing, just click on the `build and refresh`.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674308542701/49db7fc6-990f-470e-a1d4-ac1a0455f42d.png?auto=compress,format&format=webp)

This is only for testing the UI. To ensure the proper functioning of the app, you will also need to test it using an emulator in Android Studio. The emulator allows you to run and test your app in a virtual environment that mimics a real device.

Emulator
--------

You can run your app with the little green play button on the top. Additionally, the green hammer on the left side is to build the project.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674403026294/5ffea19f-6a3a-4a59-9b3a-05f06cca0453.png?auto=compress,format&format=webp)

Don't worry if you have no emulator selected as in the above screenshot. You can always create a device by going to the `Device Manager` on the left side.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674491923911/61c1472a-725f-4313-a2a9-f99292e529c2.png?auto=compress,format&format=webp)

And use `Create device` to create a new android device.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674491969453/aafc3fc8-c065-4c04-bdf4-5462931a8f12.png?auto=compress,format&format=webp)

There you can download an iso image of the latest android version and then select the ram, CPU, etc.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674403345694/e97f5b70-6a4d-4a13-b51c-cd202e59518b.png?auto=compress,format&format=webp)

Run on your phone
-----------------

If your hardware is outdated and cannot run an emulator, consider testing the app on your android phone instead. You can use `Pair Devices Using Wi-Fi` option located below the selected emulator. Keep in mind that this option needs both of your devices(laptop and phone) connected to the same network.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675086601767/8b25b57a-f333-48b0-bafd-10ac3c11740c.png?auto=compress,format&format=webp)

You will be prompted with something as follows.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675086650182/49c1a914-1cf7-420c-9e80-14bed821f111.png?auto=compress,format&format=webp)

To connect your phone using this option, go to the `Developer option`(check the documentation on [how](https://developer.android.com/studio/debug/dev-options#enable)) in your phone and select `Wireless debugging`. Then choose `Pair using QR code`. This will open your camera and you can use it to scan the QR code generated in the window. Then your phone will be connected.

You can also use `Pair using pairing code`. Click on it and choose your device, then select `Pair`. Type the pairing code in your phone and you'll be good to go.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675088186600/82811f57-2a2d-482b-9101-158109adcca7.png?auto=compress,format&format=webp)

However, this option works only for Android 11 and higher devices only. If your device doesn't have this option as well, you can use `USB Debugging`. Read [the documentation to set it up](https://developer.android.com/studio/run/device#setting-up) on different platforms.

Dive into the code
==================

It's coding time...

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1675517801592/0afb6e2c-cbcf-4094-aeef-3462a6e546e4.png?auto=compress,format&format=webp)

_NOTE_: To proceed further you need to have a solid understanding of Kotlin programming language. If you're not familiar with it, take some time and review [the documentation](https://kotlinlang.org/docs/home.html) and make yourself comfortable with the basics. Other complicated topics can be added on the fly.

Composable functions
--------------------

The traditional way of designing the UI for an android app is `XML`. However, Jetpack Compose has thrown away `XML`s.

![](https://i.imgflip.com/78gzcb.jpg)

And embraced `Composable` functions. Wait..., what is a composable function?

Composable functions are where you define your UI. It is just like a usual function in Kotlin but has the `@Composable` annotation above the function. Each composable function takes some inputs and returns some UI elements. These UI elements are then combined to form the final UI of the app.

Remember, Composable functions can be called from another Composable function only. You can't use them inside a usual function.

MainActivity.kt
---------------

Let's dive into the code in front of us. First, let's break down the `class` we have.

```
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyFirstComposeApplicationTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    Greeting("Android")
                }
            }
        }
    }
}
```

The `MainActivity` class is derived from the base class `ComponentActivity`, which is used for activities that use the Compose UI toolkit. The `ComponentActivity` class provides a convenient entry point for integrating Compose into an existing Android app.

```
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    //...
}
```

In the `MainActivity`, we have an overridden method; `onCreate()`. This is the function that is going to call first when the activity is launched. The `savedInstanceState: Bundle?` parameter in the function is used to pass in a [`Bundle`](https://developer.android.com/reference/android/os/Bundle) object that contains the state of the activity. This can be used to restore the activity to its previous state after it has been destroyed and recreated.

```
setContent {
    MyFirstComposeApplicationTheme {
    // A surface container using the 'background' color from the theme
    //...
    }
}
```

`setContent` does what its name suggests; sets the content of an activity. This is a Composable function and it takes a single argument; another Composable function, which represents the root of the UI. In this case `MyFirstComposeApplicationTheme`.

`MyFirstComposeApplicationTheme` is also a composable function that sets the theme for the activity. Note the name originated from the application name. If you click on the function name while pressing the `Ctrl`, you may find that function is written on the `Theme.kt` file is located in the `ui.theme` directory.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674405078357/e1bb3461-04d8-40e7-8108-5c20b519b986.png?auto=compress,format&format=webp)

```
MyFirstComposeApplicationTheme {
                // A surface container using the 'background' color from the theme
    Surface(
        modifier = Modifier.fillMaxSize(),
        color = MaterialTheme.colors.background
    ) {
        Greeting("Android")
    }
}
```

The `Surface` composable function inside the `MyFirstComposeApplicationTheme` is a visual container that can be used to group other composable together and apply a background color and shape to them.

Note that `setContent` is the only mandatory function that we need here. We can call `Greeting` inside the `setContent` without `MyFirstComposeApplicationTheme` and `Surface`. It would look like the following.

```
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Greeting("Android")
        }
    }
}
```

Then we have a function call to `Greeting` and have passed `Android` as an argument. `Greeting` is a composable function. In the function, we have another function call for `Text`, which takes an argument `text` and displays it.

```
@Composable
fun Greeting(name: String) {
    Text(text = "Hello $name!")
}
```

Next, you can find another annotation `Preview`. In Compose, `Preview`s are a feature that allows developers to see a live preview of their composable functions directly in the Android Studio editor. This allows developers to see how their UI will look and behave without having to run the whole app on a device or emulator.

```

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    MyFirstComposeApplicationTheme {
        Greeting("Android")
    }
}
```

By default, the background of the preview is transparent, to show the background, you can use `showBackground = true` parameter.

You can have any number of previews you want.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1674483531305/edd9069b-e289-4fd7-83e3-b396c5a03ec7.png?auto=compress,format&format=webp)

Write your first composable function
====================================

With Jetpack Compose, you're now set up to develop apps. You know how to set up an environment for jetpack compose and what's in the Android Studio default. Let's create a composable function and display some text in the preview. If you don't understand the code yet, don't worry. We'll cover it in future lessons.

```
@Composable
fun MyFirstComposableFunction(){
    Text(
        "Hello World!",
        textAlign = TextAlign.Center
    )
}
```

In the `MyFirstComposableFunction` there is a call for a composable function; `Text`, to show some texts. The `textAlign` just aligns the text to the center of the screen.

You can call this from the `MyPreview` function that we have created to preview and see what it looks like.

```
@Preview(showSystemUi = true)
@Composable
fun MyPreview(){
    MyFirstComposableFunction()
}
```

Or if you want to run it in your emulator and see, you can put the function inside the `Surface` as follows.

```

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyFirstComposeApplicationTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    MyFirstComposableFunction()
                }
            }
        }
    }
}
```

Conclusion
==========

In conclusion, we have learned about setting up the environment for using Jetpack Compose in our Android Development series. Additionally, we explored the MainActivity class and its content, as well as created a Composable function to display some texts.

I would like to express my gratitude for taking the time to read this article. As we move forward, I will dive deeper into defining the UI with Jetpack Compose. Make sure to subscribe to my newsletter to stay up-to-date.

If you found this article informative and interesting, let's connect on [**LinkedIn**](https://www.linkedin.com/in/ethan-rodrigo-b8075b259/), [**Twitter**](https://twitter.com/EthanRodrigo8), and [**Instagram**](https://www.instagram.com/ethan.rod6/)**.**