Thoughts, stories and ideas.

In this tutorial, we are going to learn about the Jetpack Compose, Android's modern, native UI toolkit to help you build better apps faster. It's stable, and ready for you to adopt in production.

As it reached stable version 1.0, there are already over 2500+ apps in the Play Store using Compose - in fact, the Play Store app itself uses Compose!

So, let quickly understand some basic things about android jetpack compose.

What is compose?

Jetpack Compose is Android’s modern toolkit for building native UI. It simplifies and accelerates UI development on Android. It is a part of the Jetpack suite of libraries.

Why we need Compose?

1. It’s Declarative

Jetpack Compose is a declarative UI framework, which means you describe your view without relying on mutation and more traditional imperative programming concepts.

2. It’s Independent

Compose is a library that isn’t coupled to the operating system. This is a major advantage for developers.

3. Less and reusable code

The Compose library is built in such a way that you can build up your UI in small, reusable building blocks rather than at the Fragment or Activity level. That composability increases code reuse and clarity.

4. Interoperable:

Compose is built to interoperate with your existing app. You can embed compose UIs within Views or Views within Compose. You can add as little as a single button to a screen, or keep that custom view you’ve created in a now Compose screen.

5. Jetpack Integration:

Compose is built to integrate with the Jetpack libraries you already know and love. With integration with Navigation, Paging, LiveData (or Flow/RxJava), ViewModel and Hilt, compose works with your existing architecture

6. 100% Kotlin

written in Kotlin programming language

7. One codebase

No need to write XML anymore.

And many more things which we going to see in upcoming tutorials. How Start Building app with compose? What do we need?

So, first of all install latest android studio click here to go to the download page.

If already installed. what are you waiting for let's get started by creating a Jetpack Compose Project.

Click on New project and Select Empty Compose Activity. Give it a name mine is My Compose App and click on finish.

The main Activity tab will open in front of you. if you already a little bit knowledge about android development with kotlin or Java, did you notice any different

Old Main Activity without compose

New Main Activity with Compose.

setContantView(R.layout.activity_main) is gone because there is no need of layouts xml files anymore we are going to use compose for all UI purposes now look at new set content it contain a function call MyComposeAppTheme which is for theming purposes which we going to learn in upcoming tutorials but first let explore further we have a function called as surface it is used as container using the 'background' color from the theme and next fun is greeting which taking a string parameter “android” these all function are composable functions

so, what is the diff between normal kotlin fun and composable fun nothing much these are return same as kotlin fun but these annotated with @Composable and should start with a Capital letter.

So, now what is we going to do is learn how to use Text, TextField, Preview, Column, Row, Button, Card, AlertDialog, etc, with this complete tutorial. So, without any further delay, let's get started...

1. textView equivalent in composable

create a composable function name PrintName inside it to disaplay a text we going to use a composable name Text()

@Composable
fun PrintName(name: String) 
    Text(
        text = "Hello $name!",
    )
}

Now go to your set content in main activity under MyComposeAppTheme fun remove every fun and call our printName function.

And run your app.

Now hover your mouse pointer over the Text() composable you will see it take many parameter we going to check each one of them

So first is Modifier

What is Modifier?

Modifiers can be used modify certain aspects of a Composable. To set them, a Composable needs to accept a modifier as a parameter. It basing used for decoration purposes.

Let’s use it


@Composable
fun PrintName(name: String) {
    Text(
        text = "Hello $name!",
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp),
        color = Color.Blue,
        fontSize = 18.sp,
        fontWeight = FontWeight.Bold,
        textAlign = TextAlign.End
    )
}

As you can see, we applied some padding to text and changes its size, Color and weight.

And you don’t need to run the app on emulator to text these changes you can find a split button between code and Design on top right corner of your editor tab click on it and build your project.

How we seeing this preview because if you noticed our main Activity file contain a composable function Name DefaultPreview()

Which is annotated with @Preview(showBackground = true)Which creating a preview of every composable fun which is inside this composable fun

Now do some change to add a new parameter lastName to our printName fun

And add a new Text composable

@Composable
fun PrintName(name: String,lastName:String) {
    Text(
        text = "Hello $name!",
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp),
        color = Color.Blue,
        fontSize = 18.sp,
        fontWeight = FontWeight.Bold,
        textAlign = TextAlign.End
    )
    Text(
        text = lastName ,
        modifier = Modifier
            .fillMaxWidth()
            .padding(8.dp),
        color = Color.Blue,
        fontSize = 14.sp,
        fontWeight = FontWeight.Bold,
        textAlign = TextAlign.End
    )
}
Text Composable

Press Ctrl+shift+F5 to build and refresh your preview.

O oh! It appear it stacks the text elements on top of each other

Why is this?

Because, if you don't provide guidance on how they should be arranged, Compose might arrange the elements in a way you don't like.

Now it time to introduce a new composable called as Column

2. What is Column in composable?

It is almost same use as Linear Layout vertical. Let do this change printName function a little bit

@Composable
fun PrintName(name: String,lastName:String) {
    Column() {
        Text(
            text = "Hello $name!",
            modifier = Modifier
                .padding(8.dp),
            color = Color.Blue,
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold,
        )
        Text(
            text = lastName,
            modifier = Modifier
                .padding(start = 8.dp,top = 2.dp,bottom = 8.dp,end = 8.dp),
            color = Color.Red,
            fontSize = 14.sp,
            fontWeight = FontWeight.Bold,
        )
    }

}
Column composable

Now it good.

Composable Column Preview

But because we removed fillMaxWidth() from text Modifiers it looking like a small box in left top corner in the phone’s screen. Let’s put It all in the canter, In column fun give a modifier

Column(modifier = Modifier.fillMaxSize(),
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Arrangement.Center
) {…} 

As you can see column only take these three things as parameter modifier for decoration and Alignment, Arrangement for content positioning.

Now let move further what if we want to print last name right side of the name Something similar like linear layout horizontal

3. Row Composable

Row(modifier = Modifier.fillMaxSize(),
    verticalAlignment = Alignment.CenterVertically,
    horizontalArrangement = Arrangement.Center
) {…}
Row Composable

Done.

4. Next is TextField which is similar to editText

Let’s add this under text function Inside the column

TextField(
    value = "some value",
    onValueChange = {
    
})

As you can see it required to parameters value type String and onValueChange type Function

If you run it on device you will see you are not able to input any these inside it lets make some change for that

Create a mutablestateof() variable on top in side your printName Composable

Wait what is MutableState

A mutable value holder where reads to the value property during the execution of a Composable function, the current RecomposeScope will be subscribed to changes of that value. When the value property is written to and changed, a recomposition of any subscribed RecomposeScopes will be scheduled. If value is written to with the same value, no recompositions will be scheduled.

val nameState = remember { mutableStateOf(TextFieldValue()) }

What is remember stands for in composable functions

Well, a remember composable remembers the given value after recomposition of that composable.

TextField(
    value = nameState.value,
    onValueChange = {
        nameState.value = it
})
TextField Composable

Add some label 😊

label = { Text(text = "User Name") }

now good to go. What if we want to display input to out Text function Let’s put all this together

@Composable
fun PrintName() {
    val nameState = remember { mutableStateOf(TextFieldValue()) }
    Row(modifier = Modifier.fillMaxSize(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.Center
    ) {
        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {
            Text(
                text = "Hello ${nameState.value.text}",
                modifier = Modifier
                    .padding(8.dp),
                color = Color.Blue,
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
            )
            TextField(
                value = nameState.value,
                onValueChange = {
                    nameState.value = it
            },
                label = { Text(text = "User Name") }
            )
        }
    }

}

You can also try OutlinedTextField

5.  Cards in Composable

Card(
    modifier = Modifier.padding(16.dp),
    elevation = 4.dp,
    shape = RoundedCornerShape(15.dp)
) {…}

Add a Image in card Body

Image(
    modifier = Modifier.size(75.dp)
        .clip(CircleShape)
        .border(
            width = 2.dp,
            color = Color.Blue,
            shape = CircleShape
        ),
    painter = painterResource(id = R.drawable.ic_launcher_foreground),
    contentDescription = null,
)

Also add Some Text And Final Result :

Card(
        modifier = Modifier.padding(16.dp),
        elevation = 4.dp,
        shape = RoundedCornerShape(15.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp)
        ) {
            Column(
                modifier = Modifier.padding(16.dp)

            ) {
                Image(
                    modifier = Modifier.size(75.dp)
                        .clip(CircleShape)
                        .border(
                            width = 2.dp,
                            color = Color.Blue,
                            shape = CircleShape
                        ),
                    painter = painterResource(id = R.drawable.ic_launcher_foreground),
                    contentDescription = null,
                )
            }
            Column(
                modifier = Modifier.padding(top = 24.dp),
                verticalArrangement = Arrangement.Center,
            ) {
                Text(
                    text = "Kp Yadav",
                    fontSize = 18.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.Black
                )
                Text(
                    text = "Android Developer",
                    fontSize = 14.sp,
                    fontWeight = FontWeight.SemiBold,
                    color = Color.LightGray
                )
            }
        }
    }
}
Card composable
Card Composable Preview

6. Button in Composable

Button(
    modifier = Modifier.padding(4.dp),
    onClick = {
    if(updateNameState.value.isNotEmpty()){
        nameState.value = updateNameState.value
    }
}){
    Text(text ="Update",fontSize=18.sp)
}

Button contain one necessary parameter onClick Function. And its body is Row scope  type so put a text composable to show name on the button That it.

7. Alert Dialog in Composable

Add a variable name showDialog

val showDialog = remember { mutableStateOf(false)}

Now if showDialog value became true we will be going to show our alertDialog

if(showDialog.value){
    OurDialog(
        showDialog.value,
        nameState
    ) { showDialog.value =false }
}

here in OurDialog Composable we pass 3 parameters 1. showDialog value, 2. NameState for showing a name in dialog body, 3. A function which we going to call  from inside the alertDialog dismiss buttons.

@Composable
fun OurDialog(showDialog:Boolean,nameState: MutableState<String>, onDismiss: () -> Unit) {
    if (showDialog){
        AlertDialog(
            onDismissRequest = { onDismiss() },
            dismissButton = { Button(onClick = onDismiss){ Text(text ="OK") } },
            confirmButton = {},
            text = {
                Column {
                    Text(text ="Name Card")
                    NameCard(nameState)
                }
            }
        )
    }
}

Here in alertDialog Composable 4 parameters required

1. On dismiss Request fun  where we called our onDismiss fun

2. dismissButton where we create a button and on click that button call same onDismiss fun

3. confirmButton we leaved it empty

4. text it contain body of our alert Dialog inside this we added a column with a text and card composable

that’s it our Alert Dialog it ready.

Summary

That's it from this tutorial. There are many other examples that you can try using Jetpack Compose.it provides a modern approach to defining your UI that enables you to separate concerns effectively. Because Composable functions are so similar to normal kotlin functions, the tools with which you write and refactor them will fit neatly into your kit of Android development skills.

In the next post, I’m going to shift the focus to create a ListView using  recyclerview  alternative in compose Lazycolumn  load images from network using coil and  json data using retrofit.

If you liked this article, please share it on social media and check out my other articles.