Jetpack Compose中的自定义可滑动开关



我想做自定义的可滑动开关,但我希望开关只从主要部分(深灰色框(滑动。问题是,我可以从任何地方滑动盒子,甚至是一排中的浅灰色部分(当深灰色盒子在另一边时(。我怎么能只从深灰色的盒子里得到手势呢。

val width = 96.dp
val squareSize = 48.dp
val swipeableState = rememberSwipeableState(0)
val sizePx = with(LocalDensity.current) { squareSize.toPx() }
val anchors = mapOf(0f to 0, sizePx to 1) // Maps anchor points (in px) to states
Box(
modifier = Modifier
.width(width)
.swipeable(
state = swipeableState,
anchors = anchors,
thresholds = { _, _ -> FractionalThreshold(0.3f) },
orientation = Orientation.Horizontal
)
.background(Color.LightGray)
) {
Box(
Modifier
.offset { IntOffset(swipeableState.offset.value.roundToInt(), 0) }
.size(squareSize)
.background(Color.DarkGray)
)
}

将可滑动修改器移动到内部框

Box(
modifier = Modifier
.width(width)

.background(Color.LightGray)
) {
Box(
Modifier
.swipeable(
state = swipeableState,
anchors = anchors,
thresholds = { _, _ -> FractionalThreshold(0.3f) },
orientation = Orientation.Horizontal
)
.offset { IntOffset(swipeableState.offset.value.roundToInt(), 0) }
.size(squareSize)
.background(Color.DarkGray)
)
}