【发布时间】:2023-02-07 20:44:20
【问题描述】:
我正在尝试使用 kotlin jetpack compose 学习 android 编程,并且正在制作一个聊天应用程序。但是,我似乎无法在按下发送按钮后传递我的 TextField 值。
我正在使用我定义的自定义可点击功能:
@Composable
fun Modifier.timedClick(
timeInMillis: Long = 2500,
defaultPercentage: Float = 0f,
content: String = "",
onClick: (Float, String) -> Unit,
interactionSource: MutableInteractionSource = remember{MutableInteractionSource()}
) = composed{
var timeOfTouch = -1L
Log.d("BUTTON", "#1 The content before LaunchedEffect is: $content")
LaunchedEffect(interactionSource){
Log.d("BUTTON", "#2 The content before LaunchedEffect is: $content")
interactionSource.interactions.onEach {
when(it){
is PressInteraction.Press ->{
timeOfTouch = System.currentTimeMillis()
Log.d("BUTTON", "#3 The content after button pressed is: ${content}")
Log.d("BUTTON", "the button has been pressed")
}
is PressInteraction.Release -> {
val currentTime = System.currentTimeMillis()
val calculatedPercentage: Float = defaultPercentage+((currentTime-timeOfTouch).toFloat()/timeInMillis)*(1-defaultPercentage)
onClick(min(calculatedPercentage, 1f),
content
)
Log.d("BUTTON", "#4 The content after button is released is: ${content}")
Log.d("BUTTON", "the button has been released, the calculated percentage is ${calculatedPercentage * 100}% and the time is ${(currentTime-timeOfTouch).toFloat()/timeInMillis}ms")
}
is PressInteraction.Cancel -> {
timeOfTouch = -1L
}
}
}
.launchIn(this)
}
Modifier.clickable (
interactionSource = interactionSource,
indication = rememberRipple(),
onClick = {}
)
}
然后我使用图像作为按钮并像这样传递文本字段值
var textFieldValue by remember { mutableStateOf("") }
TextField(
value = textFieldValue,
onValueChange = { textFieldValue = it },
modifier = Modifier.fillMaxWidth()
)
Box(modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()){
Image(
modifier = Modifier
.clip(CircleShape)
.size(70.dp)
.align(Alignment.Center)
.timedClick(
content = textFieldValue,
onClick = onClick
),
contentDescription = null,
painter = painterResource(id = R.drawable.poop3),
contentScale = ContentScale.Crop
)
}
但是,每次发送时,LaunchedEffect 中的内容变量始终为空(即在 log.d #1 中,内容会定期正确更新,但 log.d #2 仅在运行开始时调用一次而 log.d #3 和 #4 将始终显示一个空字符串。我该如何解决这个问题?
【问题讨论】:
标签: android kotlin android-jetpack-compose android-compose-textfield