I want to be able to show the status of external processes (e.g. Gps, connection to a device) in the UI using kotlin, Compose, and Material3. I am stymied by the need to be in a Composable
function to make this change, or to call a Composable
function, or to remember
a variable, or to change a remember
ed variable. I am new to all of these Android developer tools, so must be overlooking something, but can't find an answer via Google or StackOverflow.
In the simplified example below I'm using a Button
and want to change its containerColor
. What can I put at the comment line in the Thread to do that? If a Button
is completely wrong, I'm open to any kind of indicator that shows a Boolean. Or do I need to do something completely different?
package com.example.button
import android.os.Build
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.annotation.RequiresApi
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import java.lang.Thread.sleep
class MainActivity : ComponentActivity() {
@RequiresApi(Build.VERSION_CODES.Q)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
var buttonColour by remember {
mutableStateOf(Color.Blue)
}
MaterialTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
Row() {
Button(
onClick = {/*..*/ },
content = { Text("xxx") },
colors = ButtonDefaults.buttonColors(
contentColor = Color.White,
containerColor = buttonColour
)
)
}
}
}
}
Thread({
sleep(2000)
/* Change colour of button to red */
sleep(2000)
}).start()
}
}