I put UI code Text() in a function, and out of a function:
(Kotlin)
@Composable
@Preview(showBackground = true)
fun UI() {
Text("HelloWorld")
}
And I placed it inside onCreate:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
UITestTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Greeting(
name = "Android",
modifier = Modifier.padding(innerPadding)
)
}
UI()
Text("Hello World")
}
}
}
}
@Composable
@Preview(showBackground = true)
fun UI() {
Text("HelloWorld")
}
Neither of them show up. Now I know I have UI code outside of functions in my app I'm creating right now. It works perfectly. Putting it in a function was an experiment, but clearly, creating a new project removed something else that enabled the UI to work. Why does the Greeting function still work, though?
Here is the code for the the UI that works:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
WestminsterChimesTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
StartServiceButton()
}
}
}
}
}
}
fun StartServiceButton() {
val context = LocalContext.current
Button(
onClick = {
val intent = Intent(context, Service::class.java)
context.startForegroundService(intent)
}
) {
Text(text = "Start Service")
}
}
I'm going to test adding Column tomorrow, maybe that'll fix it.
it's the only difference between them I can think of.
In the old project WITH Column, you can see that UI is in the Column.
That might disprove my theory.
Also, when creating the new project in android studio, I selected "Empty Activity." I have no idea if that changes anything, just thought I'd put it out there.
You need to put the calls inside the Scaffold. That's why the Greeting shows up- it's inside the Scaffold. The Scaffold takes the entire screen.