我一直在尝试修改 Android Jetpack Compose official Documentation's example对于手势,使得偏移的状态在父 View 中被提升。
官方例子可以正常运行,但是修改后有卡顿,拖动后盒子回到原来的位置。
修改后的版本几乎和原来的差不多,除了状态被提升了。
@Composable
fun DragGesturesExampleWithHoistedState() {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.White)
) {
var offsetX by remember { mutableStateOf(0f) }
var offsetY by remember { mutableStateOf(0f) }
DragGesturesBox(
modifier = Modifier.offset {
IntOffset(offsetX.roundToInt(), offsetY.roundToInt())
},
onDrag = {
offsetX = it.x
offsetY = it.y
}
)
}
}
@Composable
fun DragGesturesBox(
modifier: Modifier = Modifier,
onDrag: (Offset) -> Unit
) {
Box(
modifier
.background(Color.Blue)
.size(50.dp)
.pointerInput("my unique key") { // Does not work with Unit either
detectDragGestures { change, dragAmount ->
change.consumeAllChanges()
onDrag(dragAmount)
}
}
)
}
@Preview
@Composable
fun DragGesturesExampleWithHoistedStatePreview() {
DragGesturesExampleWithHoistedState()
}
有什么我遗漏的吗?
最佳答案
改变
onDrag = {
offsetX = it.x
offsetY = it.y
}
到
onDrag = {
offsetX += it.x
offsetY += it.y
}
它会起作用。
关于android - Jetpack Compose 指针输入状态提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67615540/