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

Jetpack Compose应用问题:启动即显示文本,未按按钮触发

Jetpack Compose:实现点击按钮后才展示文本内容

问题根源

你的代码里,position变量在初始化时就通过Random.nextInt生成了随机值,所以应用一启动就会直接渲染对应位置的title和description文本,自然达不到“点击按钮才显示”的效果。

解决方案

添加一个布尔状态变量控制文本的显示状态,初始设为不显示;点击按钮时先更新随机位置,再切换显示状态为可见。

修改后的完整代码

val title: List<String> = mutableListOf(
    "My Name is Andrei",
    "My name is Guita",
    "My name is Samuel",
    "Andrei has a decision to make"
)

val description: List<String> = mutableListOf(
    "I am trying to learn Jetpack Compose",
    "I am an android developer",
    "Jetpack Compose has been fun with headaches",
    "Between Recycler View and LazyColumn which is best"
)

var position by remember {
    mutableStateOf(Random.nextInt(0, title.size - 1))
}
// 新增状态:控制文本是否显示
var showText by remember { mutableStateOf(false) }

val onClick = {
    position = Random.nextInt(0, title.size - 1)
    // 点击按钮后显示文本
    showText = true
}

Column(
    modifier = Modifier.fillMaxSize(),
    verticalArrangement = Arrangement.Center,
    horizontalAlignment = Alignment.CenterHorizontally
) {
    Image(
        painter = painterResource(id = R.drawable.rose),
        contentDescription = stringResource(id = R.string.flower_name),
        contentScale = ContentScale.Crop,
        modifier = Modifier.size(100.dp)
    )
    Text(text = stringResource(id = R.string.text))
    
    // 只有showText为true时才渲染文本
    if (showText) {
        Text(text = title[position])
        Text(text = description[position])
    }
    
    Button(
        modifier = Modifier.padding(vertical = 30.dp),
        colors = ButtonDefaults.buttonColors(
            contentColor = Color.Black,
            backgroundColor = Color.White
        ),
        shape = RoundedCornerShape(5.dp),
        onClick = onClick
    ) {
        Text(stringResource(id = R.string.btn_text))
    }
}

关键修改点说明

  1. 新增showText状态:用mutableStateOf(false)初始化,默认隐藏文本内容
  2. 修改点击事件:点击按钮时除了更新position,还要将showText设为true,触发文本显示
  3. 条件渲染文本:用if (showText)包裹需要控制显示的Text组件,只有满足条件才会渲染

如果需要每次点击按钮都刷新新的文本内容,当前逻辑已经满足——每次点击都会重新生成position,同时showText保持true,文本会自动更新为新内容。

内容的提问来源于stack exchange,提问作者robson idongesit samuel

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:24:27