2025年2月19日
Jetpack Composeを使用したAndroidアプリ開発において、TextFieldは最も基本的なUI要素の1つです。しかし、TextFieldを使用する際に下の画像のように文字が切れてしまうという問題に遭遇することがあります。この記事では、その原因と解決方法について説明します。
公式ドキュメント:https://developer.android.com/develop/ui/compose/state?hl=ja
この問題が発生する主な理由は以下の通りです。
以下のような解決方法が考えられます。
BasicTextFieldとは、、
BasicTextFieldを使用した時のコードは以下の通りです。
@Composable
fun CustomTextField(
value: String,
onValueChange: (String) -> Unit,
modifier: Modifier = Modifier,
hint: String = ""
) {
BasicTextField(
value = value,
onValueChange = onValueChange,
modifier = modifier
.fillMaxWidth()
.background(
color = Color.White,
shape = RoundedCornerShape(8.dp)
)
.border(
width = 1.dp,
color = Color.Gray,
shape = RoundedCornerShape(8.dp)
)
.padding(16.dp),
textStyle = TextStyle(
fontSize = 16.sp,
color = Color.Black
),
decorationBox = { innerTextField ->
Box {
if (value.isEmpty()) {
Text(
text = hint,
color = Color.Gray,
fontSize = 16.sp
)
}
innerTextField()
}
}
)
}
TextFieldを使用する場合は、カスタムパディングを設定することで問題を軽減できます:
TextField(
value = text,
onValueChange = { text = it },
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp), // カスタムパディング
textStyle = TextStyle(
fontSize = 16.sp,
lineHeight = 24.sp // 行の高さを指定
)
)
テキストフィールドの最小高さを指定することで、文字が切れる問題を防ぐことができます。
TextField(
value = text,
onValueChange = { text = it },
modifier = Modifier
.fillMaxWidth()
.sizeIn(minHeight = 48.dp) // 最小高さを指定
)