Android Day 2 Intro of State in Compose
package com.williamjiamin.greetingsfromwilliam
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ElevatedButton
import androidx.compose.ui.Alignment
import androidx.compose.ui.tooling.preview.Preview
import com.williamjiamin.greetingsfromwilliam.ui.theme.GreetingsFromWilliamTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GreetingsFromWilliamTheme {
MyWholeApp(modifier = Modifier.fillMaxSize())
}
}
}
}
@Composable
fun MyWholeApp(modifier: Modifier = Modifier,
names: List<String> = listOf("William Jiamin", "Mary", "Chen","Jack","Lilly")
) {
Column(modifier = modifier.padding(8.dp)) {
for (name in names) {
Greeting(name = name)
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
val changed = remember { mutableStateOf(false) }
val changedPadding = if (changed.value) 32.dp else 8.dp
Surface(
color = if (changed.value) Color.Green else Color.Magenta,
modifier = modifier.padding(8.dp)
) {
Column(modifier = Modifier.fillMaxWidth()){
Text(
text = if (changed.value) "Welcome to $name channel!" else "Thanks for watching $name's video!",
modifier = modifier.padding(16.dp)
)
ElevatedButton(
onClick = { changed.value = !changed.value },
modifier = modifier.align(Alignment.CenterHorizontally)
) {
Text(if (changed.value) "Checked !" else "Check It Out!")
}
}
}
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
GreetingsFromWilliamTheme {
Greeting("William Jiamin's ")
}
}