Android Day 7 Why calling Greeting multiple times don't work?
As someone who is new to composable, they may encounter some problem like this:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
OurOwnComposableTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Greeting("Android")
Greeting("Android")
Greeting("Android")
Greeting("Android")
Greeting("Android")
}
}
}
}
}
When there are multiple Greetings, it should show multiple "Hello Android" right?
But , if you run the app , you will see something like this:

Why is that?
Because we called Greeting multiple times, but there is no container to contain it. So it will just show one.
Let's add our own composable and container to contain it:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
OurOwnComposableTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
StackOfGreetings()
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "$name",
modifier = modifier
)
}
@Composable
fun StackOfGreetings() {
Column {
Row {
Column {
Greeting("1-")
Greeting("2-")
Greeting("3-")
Greeting("4-")
Greeting("5-")
}
Greeting("2-")
Greeting("3-")
Greeting("4-")
Greeting("5-")
}
Greeting("Android")
Greeting("William Jiamin")
Greeting("Youtube Channel")
Greeting("Learn-IT-Free.com")
Greeting("Learn Kotlin The Hard Way")
}
}
And you will see something like this:
