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

実践

@Composable
fun ClickToShakeView() {
    val shakeOffset = remember { Animatable(0f) }
    val coroutineScope = rememberCoroutineScope()

    fun triggerShake() {
        coroutineScope.launch {
            val vibrationPattern = listOf(-10f, 10f, -8f, 8f, -6f, 6f, -4f, 4f, 0f)
            vibrationPattern.forEach {
                shakeOffset.animateTo(
                    targetValue = it,
                    animationSpec = tween(durationMillis = 30)
                )
            }
        }
    }

    Box(
        modifier = Modifier
            .offset(x = shakeOffset.value.dp)
            .size(100.dp)
            .background(Color.Red)
            .clickable {
                triggerShake()
            },
        contentAlignment = Alignment.Center
    ) {
        Text("クリック", color = Color.White)
    }
}

説明

Animatable を使って、Viewの横方向の位置をアニメーションで動かしています。
vibrationPattern は震える動きのパターンをListにしている。ここを数字をいじれば震え方をアレンジできる。
Modifier.offset でX方向にビューを動かす。

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?