Jetpack Compose: 如何根据按钮是否启用或禁用来更改按钮边框的颜色?

huangapple go评论67阅读模式
英文:

Jetpack Compose: How to change color of a button border depending on if it is enabled or disabled?

问题

是否可以在禁用时更改边框的颜色 .border(
类似于使用 ButtonDefaults.buttonColors 来将边框颜色设置为 Color.Gray,如果按钮被禁用,并保持背景透明。

英文:

Is it possible to change the color of the border .border( when it is disabled?
Something like ButtonDefaults.buttonColors to make border color Color.Gray if the button is disabled and keeping background transparent.

@Composable
fun MyButton(
    modifier: Modifier = Modifier,
    title: String,
    isEnabled: Boolean = true,
    onClick: () -> Unit
) {
    Button(
        modifier = modifier
            .height(40.dp)
            .border(
                width = 1.dp,
                color = Color.Red,
                shape = RoundedCornerShape(16.dp)
            )
            .background(
                color = Color.Transparent,
                shape = RoundedCornerShape(16.dp),
            ),
        shape = RoundedCornerShape(16.dp),
        onClick = onClick,
        elevation = ButtonDefaults.elevation(
            defaultElevation = 0.dp,
            pressedElevation = 0.dp,
            hoveredElevation = 0.dp
        ),
        colors = ButtonDefaults.buttonColors(
            backgroundColor = Color.Transparent,
            disabledBackgroundColor = Color.Transparent,
            contentColor = Color.White,
            disabledContentColor = Color.Gray
        ),
        enabled = isEnabled
    ) {
        Text(text = title)
    }
}

答案1

得分: 2

Sure, here's the translated code:

只需在 border 修饰符的 color 属性中添加一个条件。

类似于:

.border(
    width = 1.dp,
    color = if (isEnabled) Color.Red else Color.Gray,
    shape = RoundedCornerShape(16.dp)
)
英文:

Just add a condition in the color attribute in the border modifier.

Something like:

.border(
    width = 1.dp,
    color = if (isEnabled) Color.Red else Color.Gray,
    shape = RoundedCornerShape(16.dp)
) 

huangapple
  • 本文由 发表于 2023年7月4日 22:19:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/76613581.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定