【问题标题】:I am building an app that show a list of texts when i click my button我正在构建一个应用程序,当我单击我的按钮时会显示文本列表
【发布时间】:2023-02-23 02:58:23
【问题描述】:

现在文本立即显示我运行而不是在显示之前等待点击,这是我的应用程序代码我无法查明什么是错误的,尤其是按钮方面。

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))
}
val OnClick = {
    position = Random.nextInt(0, title.size-1)
}

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

【问题讨论】:

  • 你好!请不要粘贴代码的屏幕截图。将您的代码文本粘贴到您的问题中。您可以编辑它。
  • @Tenfour04 我做了修改 请看一下
  • 您是说在第一次单击按钮之前根本不想显示任何文本吗?
  • @Tenfour04 是的,这就是我想要的

标签: android android-studio kotlin


【解决方案1】:

您需要跟踪是否到了显示文本的时间。此处最简单的方法是使用负数表示 position 不显示时的状态,因此将初始值设置为 -1

var position by remember {
    mutableStateOf(-1)
}

然后,当位置为负时,您只需不包含文本:

if (position >= 0) {
    Text(text = title[position])
    Text(text = description[position])
}

如果您希望文本在布局中占据空间,即使您还没有显示它,那么您应该将 alpha 设置为零而不是不使用它们。这是几个步骤,因为如果 position 为负则不能使用。

val textModifier = Modifier.alpha(if (position >= 0) 1f else 0f)
val textPosition = position.coerceAtLeast(0)
Text(text = title[textPosition], modifier = textModifier)
Text(text = description[textPosition], modifier = textModifier)

顺便说一句,获取随机新位置可以简化为:

position = title.indices.random()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    相关资源
    最近更新 更多