繁体   English   中英

Jetpack Compose PointerInput State 吊装

[英]Jetpack Compose PointerInput State Hoisting

我一直在尝试修改Android Jetpack Compose 官方文档的手势示例,以便在父视图中提升偏移量的 State。

官方例子可以正常运行,但是修改后有滞后,拖拽后框回到之前的position。

修改后的版本几乎与原版相似,只是吊装了 state。

@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
}

它会起作用的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM