0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JetpackComposeでドラッグ中Viewの色を変える

Posted at

はじめに

JetpackComposeでドラッグ中のViewを拡大する
前回の↑こちらに記事に、「押している間は色を変える」という処理を追加しました。
よければそちらもご覧ください。
それ以外にも軽く修正を含みます。

実践

@Composable
fun ScalableButton(
    modifier: Modifier = Modifier,
    onClick: () -> Unit,
    content: @Composable () -> Unit
) {
    // 押下状態
    var pressed by remember { mutableStateOf(false) }

    // 拡大アニメーション
    val scale by animateFloatAsState(
        targetValue = if (pressed) 1.1f else 1f,
        animationSpec = spring(
            dampingRatio = Spring.DampingRatioMediumBouncy,
            stiffness = Spring.StiffnessLow
        ),
        label = "scale"
    )

    // 色アニメーション
    val backgroundColor by animateColorAsState(
        targetValue = if (pressed) Color(0xFF1565C0) else Color(0xFF2196F3),
        animationSpec = tween(durationMillis = 150),
        label = "backgroundColor"
    )

    Box(
        modifier = modifier
            .graphicsLayer(
                scaleX = scale,
                scaleY = scale
            )
            .background(backgroundColor, shape = CircleShape)
            // ↓ Compose標準の押下検知+クリックを統合
            .combinedClickable(
                onClick = { onClick() },
                onLongClick = {}, // 長押し不要なら空でOK
                onClickLabel = null,
                onLongClickLabel = null,
                interactionSource = remember { MutableInteractionSource() },
                indication = null // Rippleを消したい場合
            )
            // ↓ 押している間を監視
            .pointerInput(Unit) {
                awaitEachGesture {
                    val down = awaitFirstDown()
                    pressed = true
                    try {
                        // 指を離す or キャンセルされるまで待つ
                        waitForUpOrCancellation()
                    } finally {
                        pressed = false
                    }
                }
            },
        contentAlignment = Alignment.Center
    ) {
        content()
    }
}

Box(
    modifier = Modifier
    contentAlignment = Alignment.Center // 中央に配置
) {
    ScalableButton(
        onClick = { println("Clicked!") },
        modifier = Modifier.size(120.dp)
   ) {
        Text(
            text = "押して!",
            color = Color.White,
            fontSize = 18.sp
        )
    }
}

Screen_recording_20251012_184053.gif

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?