0
0

JetpackComposeでアニメーションを使った表示・非表示の切り替え

Posted at

実践

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
            .padding(40.dp)
    ) {

        var isVisible by remember {
            mutableStateOf(true)
        }
        val animation by animateFloatAsState(
            targetValue = if (isVisible) 1.0f else 0f,
        )
        Box(
            modifier = Modifier
                .size(200.dp)
                .graphicsLayer {
                    alpha = animation
                }
                .clip(RoundedCornerShape(8.dp))
                .background(Color.Green)
        ) {}

        Button(onClick = {
            isVisible = !isVisible
        }) {
            Text(text = "切り替え")
        }
    }
}

Record_2024-04-28-20-21-10_703d6d0c1a2cc5d78cdb74dea5dc787d (online-video-cutter.com).gif

説明

サクッと説明します。
animateFloatAsStateはアニメーションの使うStateを設定しておけます。
今回の場合はif文で分岐させてアニメーションのvalueの中身を1.0fか0fかで切り替えられるようにしています。
(0.5fとかを設定すると半透明になる。)
ここまでに設定しておいたアニメーションをgraphicsLayerに渡します。

その後、ボタンでアニメーションのvalueに設定する変数を切り替えるようにしています。

参考

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