How can a reference be correctly made so that the text in the TopAppBar
changes depending on the device's hour of day? I seem to have gotten lost with the Text declaration.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Demo1Theme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
Scaffold() {
Column {
TW()
}
}
}
}
}
}
}
@Composable
fun Greeting(name: String) {
Text(text = "Hello $name!")
}
@Composable
fun TimeOfDay(time: String) {
Text(text = "The $time")
val cal: Calendar = Calendar.getInstance()
val hour: Int = cal.get(Calendar.HOUR_OF_DAY)
var mainMessage: String? = null
when (hour) {
in 6..11 -> {
mainMessage = "Morning"
}
in 12..16 -> {
mainMessage = "Afternoon"
}
in 17..20 -> {
mainMessage = "Evening"
}
in 21..23 -> {
mainMessage = "Night"
}
else -> {
mainMessage = "Morning"
}
}
}
@Composable
fun TW() {
Scaffold(
topBar = {
TopAppBar(
title = {
TimeOfDay(time = "?")
},
elevation = 12.dp
)
}, content = {
Greeting("Android")
}
)
}
CodePudding user response:
Try this once.
fun getGreetingMessage(): String {
val c = Calendar.getInstance()
return when (c.get(Calendar.HOUR_OF_DAY)) {
in 6..11 -> "Good Morning"
in 12..16 -> "Good Afternoon"
in 17..20 -> "Good Evening"
in 21..23 -> "Good Night"
else -> "Good Morning"
}
and in TopAppBar
TopAppBar(
title = {
Text(
text = getGreetingMessage(),
)
},
)
CodePudding user response:
You can achieve this by using LaunchedEffect like this
@Composable
fun Test() {
var hour by remember { mutableStateOf(Calendar.getInstance().get(Calendar.HOUR_OF_DAY)) }
LaunchedEffect(Unit) {
while (true) {
hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY)
delay(1000) // Update hour every seconds
}
}
Box(
Modifier
.fillMaxSize()
.systemBarsPadding()) {
Column {
Text(text = "$hour h")
Text(text = getPeriod(hour))
}
}
}
private fun getPeriod(hour: Int) = when (hour) {
in 6..11 -> {
"Morning"
}
in 12..16 -> {
"Afternoon"
}
in 17..20 -> {
"Evening"
}
in 21..23 -> {
"Night"
}
else -> {
"Morning"
}
}