SRJ
SRJ

Reputation: 309

How to change Composable Button Icon/Bitmap after Creation

I want to be able to change the image on a button later in my program - not during creation.

My main class

class MainActivity : ComponentActivity() {
    lateinit var button: Unit

...

setContent {
    button = WearApp()
}

WearApp is composable

@Composable
fun WearApp() {
    var _button: Unit = println("Fake Empty Initialization")
    MosaicTheme {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Transparent),
            contentAlignment = Alignment.Center
        ) {
            _button  = Button(
                onClick = {
             ...
        }
        return _button

So back in MainActivity I have a variable button: Unit. How do I work with that as a Button? How do I change the image on the button?

Upvotes: 0

Views: 123

Answers (2)

Turtlepaw
Turtlepaw

Reputation: 593

You can do this with mutable states and enums:

enum class Icon {
    DEFAULT,
    // You can add more icons here
}

@Composable
fun WearApp() {
    var buttonIcon by remember { mutableStateOf<Icon>(Icon.DEFAULT) }
    MosaicTheme {
        Box(
            modifier = Modifier
                .fillMaxSize()
                .background(Color.Transparent),
            contentAlignment = Alignment.Center
        ) {
          Button(onClick = {
            // You can set a new icon
            // buttonIcon = Icon.NEW_ICON
          }) {
            if(buttonIcon == Icon.DEFAULT) Icon(/* ... */)
            Text(text = "Button")
          }
        }
}

Upvotes: 0

Nrohpos
Nrohpos

Reputation: 447

I assume that you want to change an image when you need it to update.

If that the case, you need you have a state of icon to store it and use in button.

Here is example.

var image by remember {
    mutableIntStateOf(androidx.core.R.drawable.ic_call_answer_video_low)
}
StackoverflowTheme {
    Surface(
        modifier = Modifier.fillMaxSize(),
        color = MaterialTheme.colorScheme.background
    ) {
       Column (verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally){
           Button(onClick = {
               image =  androidx.core.R.drawable.ic_call_answer
           }) {
               Text(text = "Okay")
               Icon(painter = painterResource(id = image), contentDescription = "Okay-Image")
           }
       }
    }
}

I only test with the click function. Please take this as an example.

enter image description here

Upvotes: 0

Related Questions