JetpackComposeで上下左右のドラッグ、スワイプ操作の検知
コード(成功例)
下記コードでドラッグ操作のx軸y軸の距離で大きい方向にテキストを書き換えられます。
@Composable fun Drag() { var state by remember { mutableStateOf("-") } Box( modifier = Modifier .fillMaxSize() .pointerInput(Unit) { detectDragGestures( onDrag = { change: PointerInputChange, dragAmount: Offset -> change.consumeAllChanges() val (x, y) = dragAmount if (abs(x) > abs(y)) { state = if (x > 0) ">" else "<" } else { state = if (y > 0) "v" else "^" } }, ) } ) { Column(modifier = Modifier.align(Alignment.Center)) { Text(state, fontSize = MaterialTheme.typography.h1.fontSize) } } }
コード(失敗例)
こちらは読む必要はないです。
@OptIn(ExperimentalMaterialApi::class) @Composable fun NotWorkSwipe() { val squareSize = 48.dp val swipeableState = rememberSwipeableState("-") val sizePx = with(LocalDensity.current) { squareSize.toPx() } val horizontalAnchors = mapOf(0f to "<", sizePx to ">", 100f to "-") // Maps anchor points (in px) to states val verticalAnchors = mapOf(0f to "^", sizePx to "v", 100f to "-") // Maps anchor points (in px) to states Box( modifier = Modifier .fillMaxSize() .swipeable( state = swipeableState, anchors = verticalAnchors, orientation = Orientation.Vertical ) .swipeable( state = swipeableState, anchors = horizontalAnchors, orientation = Orientation.Horizontal ) ) { Column(modifier = Modifier.align(Alignment.Center)) { Text(swipeableState.currentValue, fontSize = MaterialTheme.typography.h1.fontSize) } } }
swipeableという修飾子をはじめに見つけたのですがこれは水平か鉛直かの方向を指定する必要がありました。 swipeable修飾子を重ねがけしたら出来るのではと思いましたが後ろのswipeable のみ適用される結果となりました。