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?

Composeで表示・非表示のアニメーションと レイアウトずれ防止対応を両立する

0
Posted at

はじめに

以前のこちらの記事Compose の Text("")minLines = 1 でも高さが 0 になるで、スペース埋めでレイアウトずれを防ぐ方法を紹介しました。
今回は「テキストをアニメーション付きで表示・非表示したい」という場合に、同じ問題がどう起きるかと、その解決策を紹介します。

AnimatedVisibility を使うとレイアウトがずれる

Compose にはコンテンツの表示・非表示をアニメーション付きで切り替える AnimatedVisibilityというコンポーザブルがあります。

  AnimatedVisibility(visible = isVisible) {
      Text(text = "表示したいテキスト")
  }  

一見良さそうですが、AnimatedVisibilityvisible = false のとき高さが 0 になるのが仕様です。アニメーション中に高さが変化するため、フェードしながらレイアウト全体がずれます。

解決策

前回紹介したスペース埋めに、animateFloatAsStatealpha をアニメーションさせることで、高さを固定しつつフェードも実現できます。

  val alpha by animateFloatAsState(                                                               
      targetValue = if (isVisible) 1f else 0f,
  ) 
  
   
  Text(                                                                                             
      text = if (isVisible) "表示したいテキスト" else " ",                                        
      color = Color.Black.copy(alpha = alpha),
      minLines = 1,
  ) 

高さはスペースで常に確保しつつ、alpha だけをアニメーションさせることでレイアウトのずれなしにフェードイン・フェードアウトができます。


アニメーションを付けたい場合でも、前回のスペース埋めは有効です。AnimatedVisibility ではなく alpha のアニメーションと組み合わせることでレイアウトのずれなしにフェードが実現できます。

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?