You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何合并两个按钮功能?Android Kotlin Compose骰子应用改造求助

解决方案

要实现一个按钮同时摇出两个骰子的随机结果,只需保留一个按钮,并在其点击事件中同时更新两个骰子的状态值即可,具体修改如下:

修改后的完整代码

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            DiceRollerTheme {
                DiceRollerApp()
            }
        }
    }
}


@Preview
@Composable
fun DiceRollerApp() {
    DiceWithButtonAndImage(modifier = Modifier
        .fillMaxSize()
        .wrapContentSize(Alignment.Center)
    )
}

@Composable
fun DiceWithButtonAndImage(modifier: Modifier = Modifier) {
    var result by remember { mutableStateOf(1) }
    var result2 by remember { mutableStateOf(1) }
    
    // 抽取出复用函数,减少重复的图片匹配逻辑
    fun getDiceImage(diceValue: Int): Int {
        return when (diceValue) {
            1 -> R.drawable.dice_1
            2 -> R.drawable.dice_2
            3 -> R.drawable.dice_3
            4 -> R.drawable.dice_4
            5 -> R.drawable.dice_5
            else -> R.drawable.dice_6
        }
    }

    Column(
        modifier = modifier,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Image(
            painter = painterResource(getDiceImage(result)),
            contentDescription = result.toString()
        )
        Image(
            painter = painterResource(getDiceImage(result2)),
            contentDescription = result2.toString()
        )
        Spacer(modifier = Modifier.height(16.dp))

        // 单个按钮,点击时同时更新两个骰子的随机结果
        Button(onClick = { 
            result = (1..6).random()
            result2 = (1..6).random()
        } ) {
            Text(stringResource(R.string.roll))
        }
    }
}

关键修改说明

  • 删除其中一个Button组件,仅保留一个摇骰按钮
  • 在保留的按钮onClick逻辑中,同时对result和result2赋值随机数,点击一次即可同步刷新两个骰子的显示
  • 额外优化:将重复的骰子图片匹配逻辑封装为getDiceImage函数,让代码更简洁易维护

内容的提问来源于stack exchange,提问作者Kurt Brearley

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 00:42:15