TextFieldの基本
var text by remember { mutableStateOf("") }
TextField(
value = text,
onValueChange = { text = it }
)
このonValueChangeの中で制限を追加していきます
文字数制限
TextField(
value = text,
onValueChange = {
if (it.length <= 10) {
text = it
}
},
label = { Text("10文字まで") }
)
- 入力された値をそのまま代入しない
- 条件を満たしたときだけ state を更新する
数値のみ入力
TextField(
value = text,
onValueChange = {
if (it.all { char -> char.isDigit() }) {
text = it
}
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number
)
)
- KeyboardType.Number はキーボード表示を変えるだけ
- 入力値の制限は別途必要
文字数 + 数値制限
TextField(
value = text,
onValueChange = {
if (it.length <= 6 && it.all { char -> char.isDigit() }) {
text = it
}
}
)
- 郵便番号、年齢、ID入力などに使える
空白禁止
TextField(
value = text,
onValueChange = {
text = it.filterNot { char -> char.isWhitespace() }
}
)
- singleLine = true を指定する
- コピペで改行が入る可能性も考える
小数点を許容
val regex = Regex("^\d*(\.\d*)?$")
TextField(
value = text,
onValueChange = {
if (regex.matches(it)) {
text = it
}
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Decimal
)
)
- . を1つだけ許可する
電話番号っぽい整形
TextField(
value = phoneNumber,
onValueChange = {
phoneNumber = formatPhoneNumber(it)
},
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Phone
)
)
- keyboardOptionsを指定してそれっぽくできる