Create Composables with Jetpack Compose

Sep 10 2024 · Kotlin 1.9, Android 14, Android Studio Jellyfish | 2023.3.1

Lesson 02: Modify Composables

Demo

Episode complete

Play next episode

Next
Transcript

Open the Starter project in the 02-modify-composables directory of the m3-cjp-materials repo in Android Studio Jellyfish or later.

Wait for the project to be built.

In this demo, you’ll work with modifiers.

Open the MainActivity.kt file.

You’ll notice an empty composable named HelloCompose already created for you.

First, add a button.

Replace the TODO with the following code:

Button( 
	onClick = { Log.d("HelloCompose", "Hello Compose clicked!") },  
	content = { Text(text = "Click Me") }
)

Add the following missing imports as well:

import androidx.compose.material.Button
import androidx.compose.material.Text

In the snippet above:

  • You created a button with the text label “Click Me”.
  • Then, you defined the onClick action for the button, such that it logs “Hello Compose clicked!” to the console.

Build and run the app to see the button on the screen. Open logcat. If you click the button, you’ll see the message printed on logcat.

Time to add modifiers.

Center the button on the screen and make it take the entire screen width. First, update the signature of the HelloCompose function to accept a modifier, and use the modifier in the button:

@Composable  
fun HelloCompose(modifier: Modifier = Modifier) {  
	Button(  
		modifier = modifier,  
		onClick = { Log.d("HelloCompose", "Hello Compose clicked!") },  
		content = { Text(text = "Click Me") }
	)  
}

Next, update the box with the following modifiers:

Box(modifier = Modifier  
	.background(Color.Yellow.copy(alpha = 0.4f))  
	.padding(16.dp)  
	.fillMaxSize()  
)

Add the missing imports:

import androidx.compose.ui.graphics.Color

With these changes, the parent box will take up the entire available screen size, use a shade of pale yellow for its background and add a uniform padding of 16dp on all sides.

Finally, modify the HelloCompose call with modifiers.

HelloCompose(  
	modifier = Modifier  
		.fillMaxWidth()  
		.align(Alignment.Center),  
)

Add the missing import:

import androidx.compose.ui.Alignment

With these modifiers in place, your button should now be centered on the screen and take up the entire available screen width.

Build and run the app. For some fun, try to rotate the button by 30 degrees.

Add the following modifier to the button composable.

Button(modifier = modifier.rotate(30f)),

Great job!

That concludes this demo. Continue with the lesson for a summary.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion