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?

AndroidでCompose の `Text("")` は `minLines = 1` でも高さが 0 になる件

0
Posted at

TextField のバリデーションエラーメッセージなど、条件によって表示・非表示が切り替わるテキストを実装するとき、こんなコードを書きがちです。

  var input by remember { mutableStateOf("") }
  val errorMessage = if (input.length > 10) "10文字以内で入力してください" else ""
                                                                                         
  Column {
      TextField(                                                                         
          value = input,                                                               
          onValueChange = { input = it },
      )
      Text(
          text = errorMessage,
          color = Color.Red,
          fontSize = 12.sp,                                                              
          minLines = 1,
      )                                                                                  
  }  

minLines = 1 を指定しているので高さは確保されてそうに見えますが、text = "" のとき Composeは minLines を無視して高さ 0 にすることがあります。
その結果、エラーメッセージが出た瞬間に TextField が上にズレるレイアウトずれが起きます。

解決策

空文字のときはスペース " " を渡して高さを確保し、色を Color.Transparent にして見た目を透明にします。

Text(                                                                                
    text = errorMessage.ifEmpty { " " },                                               
    color = if (errorMessage.isNotEmpty()) Color.Red else Color.Transparent,
    fontSize = 12.sp,                                                                  
    minLines = 1,                                                                    
)
 

こうすることでエラーの有無にかかわらず常に1行分の高さが確保され、レイアウトずれが起きなくなります。

# まとめ
minLines で高さを確保したいときは、空文字ではなくスペースを渡す。

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?