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
}
setContentView
is replaced bysetContent
.- The
setContent
returns 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.
setContent
has 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,
setContent
accepts a function. - Also it accepts not just any function, but a
composable
function. - We have
setContent
that 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
annotate
the function with@compose
, You would end up with an errorFunctions which invoke @Composable functions must be marked with the @Composable annotation