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

防止按钮连点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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()
}
}

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

使用方法:

1
2
3
4
5
6
7
8
9
10
11
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即可。

去除涟漪效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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即可。