Basics of Jetpack Compose: Day 1 of #100DaysOfJetpackCompose

Basics of Jetpack Compose: Day 1 of #100DaysOfJetpackCompose

ยท

2 min read

I think in 2023, Google is going to go all-in on Jetpack Compose, the way it did with Kotlin. And the industry is going to see a major shift from XML-based UI to Compose.

So, I'm starting a #100DaysOfJetpackCompose on Twitter today to document my learnings. Here's a blog post version of the Day 1 thread:

Let's Go ๐Ÿš€๐Ÿš€

Composable Functions

In Jetpack Compose instead of defining the UI of an Activity in a separate layout file, you define the app's UI programmatically using "composable functions".

Composables are parts of UI that are defined separately and can be re-used effectively.

A composable function is a function with an @Composable annotation before it, like in this simple compose activity:

/*..imports..*/

class MainActivity : ComposeActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent{
            Header("Android")
        }
    }
}

@Composables
fun Header(name: String) {
    Text(text = "Hello $name!")
}

Previews

To see a preview of your UI without running the app, create a separate composable with @Preview annotation, like this:

/*.. imports. .*/
class MainActivity : ComponentAct ivity() {
    override fun onCreate( saved InstanceState: Bundle?) {
        super.onCreate( savedInstanceState)
        setContent {
            ComposeBasicsTheme {
                Surface( color = MaterialTheme.colors.background) {
                        Header("Android")
                }
           }
        }
    }
}

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

@Preview( fontScale = 1.5f)
@Preview( showBackground = true)
@Composable
fun DefaultPreview() {
    ComposeBasicsTheme {
    Header("Android")
}

The @Preview annotation allows you to check how your UI looks with changes in settings such as font scale and background as seen in the above example.

And since I used @Preview with different parameters, we can see two different previews:

You can create as many Preview functions as you want to see how your UI looks with different properties.

ConstraintLayout is gone!

This is the new way to organize your UI elements is using Rows s and Column s like this:

That's it for today. I'll be back again tomorrow with more notes as I learn Compose. You can follow me on Twitter for updates. Till then, Keep building the Future!

ย