Setting the content of the screen - devrath/urban-octo-jetpack-compose GitHub Wiki
-
There is no layout in the resource directory.
-
Our activity class extends
ComponentActivity.
class MainActivity : ComponentActivity() {
// -- > Source code
}
setContentViewis replaced bysetContent.- The
setContentreturns a composable. - To define a UI in android, we write functions in kotlin, these functions are annotated with
@composable - It is a common web development concept where we separate the UI into components that can be reused.
setContenthas all the components of the composable for the current screen.
class MainActivity : ComponentActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
}
}
}
- Now going more in detail for
setContent {} - As seen below,
setContentaccepts a function. - Also it accepts not just any function, but a
composablefunction. - We have
setContentthat accepts composable and that composable can have another composable and so on
public fun ComponentActivity.setContent(
parent: CompositionContext? = null,
content: @Composable () -> Unit
) {
// Some code
}
- Finally add a compose function for the
setContent
class MainActivity : ComponentActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GreetingScreen("Hello World")
}
}
@Composable
private fun GreetingScreen(displayText: String) {
Text(text = displayText)
}
}
- If you don't
annotatethe function with@compose, You would end up with an errorFunctions which invoke @Composable functions must be marked with the @Composable annotation