按下 Compose Surface 时更改 alpha(可点击修改器)

时间:2021-03-11 12:08:41

标签: android android-jetpack-compose

我在 clickable 上使用 Surface 修饰符,并希望创建一个自定义指示,使表面(及其内容)在按下时显示 0.5 alpha。不过好像只能用来绘制额外的UI。

如何在按下时使用 0.5 alpha 重绘 Surface

Surface(
   modifier = Modifier.clickable(interactionSource = remember { MutableInteractionSource() }, indication = CustomIndication, onClick = onClick)
    ) {

    ...

}

3 个答案:

答案 0 :(得分:2)

使用 1.0.0 修饰符中的 1.0.0-beta07(使用 clickable 测试),您可以指定 Indication 参数。您可以使用由 rememberRipple 更改颜色定义的默认波纹。

类似于:

val interactionSource = remember { MutableInteractionSource() }

//clickable modifier
val clickable = Modifier.clickable(
    interactionSource = interactionSource,
    indication = rememberRipple(color = /* use you custom color */
       MaterialTheme.colors.primary.copy(alpha = 0.5f))
) { /* update some business state here */ }


Surface(modifier = clickable){
     //...
}

否则你可以使用类似的东西:

val interactionSource = remember { MutableInteractionSource() }
val isPressed by interactionSource.collectIsPressedAsState()
val backgroundAlpha = if (isPressed) 0.5f else 1f

Surface(
    modifier = Modifier.clickable(true){},
    color= MaterialTheme.colors.secondary.copy(alpha = backgroundAlpha)
) {
   //....
}

答案 1 :(得分:1)

试试这个:

var isPressed by remember { mutableStateOf(false) }
val backgroundAlpha = if (isPressed) 0.5f else 1f
Surface(
    modifier = Modifier
        .clickable {  }
        .pointerInput(Unit) {
            detectTapGestures(
                onPress = {
                    isPressed = true
                    val success = tryAwaitRelease()
                    if (success) isPressed = false
                    else isPressed = true
                }
            )
        },
    color = MaterialTheme.colors.primary.copy(alpha = backgroundAlpha)
) {
    ...
}

答案 2 :(得分:0)

@Composable
fun AlphaSurface(){
    val isClicked = remember { mutableStateOf(false) }
    val alphaValue = if(isClicked.value) 0.5f else 1f
        Surface(
            modifier = Modifier.clickable {
                isClicked.value = isClicked.value.not() // toggle the value 
            }.fillMaxHeight().fillMaxWidth(),
            color = MaterialTheme.colors.primary.copy(alpha = alphaValue )
            ) {

        }
}