创建后如何更改可组合按钮图标/位图

问题描述 投票:0回答:1

我希望能够稍后在程序中更改按钮上的图像 - 而不是在创建过程中。

我的主课

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

...

setContent {
    button = WearApp()
}

WearApp 是可组合的

@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

回到 MainActivity 我有一个变量按钮:Unit。 我如何将其用作按钮?如何更改按钮上的图像?

android android-jetpack-compose wear-os
1个回答
0
投票

我假设您想在需要更新时更改图像。

如果是这种情况,您需要有一个图标状态来存储它并在按钮中使用。

这是示例。

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")
           }
       }
    }
}

我只用点击功能进行测试。请以此为例。

© www.soinside.com 2019 - 2024. All rights reserved.