Android使用Jetpack Compose开发防止按钮连点及去除涟漪效果

2024-04-25 16:16:12 浏览数 (1)

防止按钮连点

代码语言:javascript复制
import android.annotation.SuppressLint
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import kotlinx.coroutines.delay

@SuppressLint("ModifierFactoryUnreferencedReceiver")
fun Modifier.debouncedClickable(delay: Long = 500, onClick: () -> Unit) = composed {
    //按钮是否可点击
    var canClick by remember {
        mutableStateOf(true)
    }
    LaunchedEffect(key1 = canClick, block = {
        if (!canClick) {
            delay(delay)
            canClick = true
        }
    })

    Modifier.clickable(canClick) {
        canClick = false
        onClick()
    }
}

这里准确来说不是按钮防抖,也不是节流,只是控制按钮在短时间不能连点。

使用方法:

代码语言:javascript复制
Box(
    modifier = Modifier
        .align(Alignment.Bottom)
        .padding(0.dp, 0.dp, 6.dp, 0.dp)
        .size(72.dp, 28.dp)
        .clip(RoundedCornerShape(6.dp))
        .debouncedClickable {
            event(BtnType.UNINSTALL, appItem)
        }) {
    ZBtnView2("卸载")
}

也就是把clickable更换为debouncedClickable即可。

去除涟漪效果

代码语言:javascript复制
import android.annotation.SuppressLint
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import kotlinx.coroutines.delay

@SuppressLint("ModifierFactoryUnreferencedReceiver")
inline fun Modifier.noRippleClickable(crossinline onClick: () -> Unit): Modifier = composed {
    clickable(indication = null,
        interactionSource = remember { MutableInteractionSource() }) {
        onClick()
    }
}

使用方法:

clickable更换为noRippleClickable即可。

0 人点赞