TextFieldのPaddingをModifierで指定しても背景のViewのPaddingが変更できません
TextFieldの実装を見るとわかるのですが内部でBasicTextFieldを使用していて背景のViewはDecorationBoxで実装されています
Paddingを調整する方法は以下があります
・背景色とアンダーラインを透明にしてPaddingの16.dpを活かして配置する
※ paddingは変更できないがカーソルの描画領域のスペースも確保すべきなので見た目で対処
・BasicTextFieldで実装しdecorationBoxを独自に実装
・BasicTextFieldで実装しTextFieldDefaults.DecorationBoxのcontentPaddingで指定
TextFieldのまま/上記3点の実装した場合は以下のようになります
※ BasicTextFieldの配置は左に16.dpのPaddingを指定してます
背景色とアンダーラインを透明
var text by remember { mutableStateOf("テキスト") }
TextField(
value = text,
onValueChange = { text = it },
colors = TextFieldDefaults.colors(
focusedContainerColor = Color.Transparent,
unfocusedContainerColor = Color.Transparent,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
)
)
BasicTextFieldで実装しdecorationBoxを独自に実装
DecorationBox相当の装飾は下線のみ実装
val drawLine = true
BasicTextField(
value = text,
onValueChange = { text = it },
textStyle = LocalTextStyle.current.copy(
color = MaterialTheme.colorScheme.onSurface
),
) { innerTextField ->
Column {
innerTextField()
if (drawLine) {
Spacer(Modifier.height(1.dp))
Divider(thickness = 1.dp, color = MaterialTheme.colorScheme.onSurface)
}
}
}
BasicTextFieldで実装しTextFieldDefaults.DecorationBoxのcontentPaddingで指定
DecorationBoxのshapeが目立つので四角に変更してます
val enabled = true
val singleLine = true
val visualTransformation = VisualTransformation.None
val interactionSource = remember { MutableInteractionSource() }
BasicTextField(
value = text,
onValueChange = { text = it },
textStyle = LocalTextStyle.current.copy(
color = MaterialTheme.colorScheme.onSurface
),
enabled = enabled,
singleLine = singleLine,
visualTransformation = visualTransformation,
interactionSource = interactionSource,
) { innerTextField ->
TextFieldDefaults.DecorationBox(
value = text,
innerTextField = innerTextField,
enabled = enabled,
singleLine = singleLine,
visualTransformation = VisualTransformation.None,
interactionSource = interactionSource,
shape = RectangleShape, // TextFieldDefaults.shape
contentPadding = PaddingValues(0.dp)
)
}
Android Studio Giraffe 2022.3.1 built on June 29, 2023