是否可以对 fab 实现长按,在 fab 顶部显示带标签的小按钮,而无需额外组件?
如果不是如何使用附加组件来实现但视觉结果相同?
FloatingActionButton(
onClick = {
/* onClick - event */
},
modifier = Modifier
.padding(10.dp),
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(8.dp),
) {
Icon(
imageVector = Icons.Default.PlayArrow
contentDescription = stringResource(id = R.string.edit),
modifier = Modifier.padding(8.dp, 0.dp, 0.dp, 0.dp),
)
TextView(
text = stringResource(id = R.string.start),
modifier = Modifier.padding(8.dp, 0.dp, 8.dp, 0.dp),
)
}
}
我尝试使用其他组件代替 FAB,但无法让它的行为和外观相同。
您可以通过两种方式构建它,您需要复制粘贴 FloatingActionButton 的源代码并使用不带 onClick 参数的 Surface 进行一些修改,或者使用
InteractionSource
来确定 fab 被按下的时间。
我将发布第二个选项,因为这个选项比复制粘贴和修改解决方案更容易。
您也可以将此解决方案应用于
Button
,因为它也需要 InteractionSource
作为参数。
@Preview
@Composable
private fun Test() {
val context = LocalContext.current
val interactionSource = remember { MutableInteractionSource() }
val viewConfiguration = LocalViewConfiguration.current
var isLongPress by remember {
mutableStateOf(false)
}
LaunchedEffect(interactionSource) {
var pressTime = 0L
interactionSource.interactions.collect { interaction ->
when (interaction) {
is PressInteraction.Press -> {
isLongPress = false
pressTime = System.currentTimeMillis()
}
is PressInteraction.Release -> {
val currentTime = System.currentTimeMillis()
if (currentTime - pressTime > viewConfiguration.longPressTimeoutMillis){
Toast.makeText(context, "Long click", Toast.LENGTH_SHORT).show()
}else {
Toast.makeText(context, "onClick", Toast.LENGTH_SHORT).show()
}
}
is PressInteraction.Cancel -> {
}
}
}
}
FloatingActionButton(
interactionSource = interactionSource,
onClick = {},
modifier = Modifier
.padding(10.dp),
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.colorScheme.onSecondaryContainer,
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(8.dp),
) {
Icon(
imageVector = Icons.Default.PlayArrow,
contentDescription = null,
modifier = Modifier.padding(8.dp, 0.dp, 0.dp, 0.dp),
)
Text(
text = "Start",
modifier = Modifier.padding(8.dp, 0.dp, 8.dp, 0.dp),
)
}
}
}