I am trying to use remember from jetpack compose in order to change the background colour of the Elevated button when it's clicked . So, when I set a variable with a value of MaterialTheme.colorScheme.primary, it's showing error at colorScheme similarly its showing the same error for MaterialTheme.colorScheme.secondary . So, I don't quite understand where am I going wrong. I am relatively new to the Jetpack compose. Below is my code.
MainActivity.kt
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.compose.ui.theme.ComposeTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeTheme {
// A surface container using the 'background' color from the theme
MyApp(modifier = Modifier.fillMaxSize())
}
}
}
}
@Composable
fun MyApp(modifier: Modifier=Modifier,
names:List<String> = listOf("World","Compose")
){
Column(modifier = modifier.padding(vertical = 4.dp)) {
for (name in names) {
Greeting(name = name)
}
}
}
@Composable
fun Greeting(name: String) {
// Define a state to hold the button color
var buttonColor by remember {
mutableStateOf(MaterialTheme.colorScheme.primary) //colorScheme is giving error
}
Surface(
color = buttonColor,
modifier = Modifier.padding(vertical = 4.dp, horizontal = 8.dp)) {
Row(modifier = Modifier.padding(24.dp)) {
Column(modifier = Modifier.weight(1f)){
Text(text = "Hello")
Text(text = name)
}
ElevatedButton(onClick = {
buttonColor = MaterialTheme.colorScheme.secondary //colorScheme is giving error
}) {
Text(text = "Show more")
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
ComposeTheme {
MyApp()
}
}