Wanna create TextField for phone number. Need help with set cursor in field always in end of string
What i trying to do: When got new number in field , i get all numbers that already entered, than append underscore( _ ) for have at least 11 string length, and than return string with numbers or "_" by substring:
return "+7(${template.substring(1, 4)}) ${template.substring(4,7)} ${template.substring(7,9)} ${template.substring(9, 11)}"
If cursor always in end it works, but if not the numbers order is broken
Full code:
@Composeble
@Composable
fun PhoneNumberEditText(
phoneNumState: MutableState<String>,
modifier: Modifier = Modifier,
imeAction: ImeAction = ImeAction.Done,
onImeAction: () -> Unit = {}
) {
TextField(
shape = RoundedCornerShape(16.dp),
value = phoneNumState.value,
onValueChange = { value ->
phoneNumState.value = value
val digits = phoneNumState.value.toCharArray().filter { it.isDigit() }
phoneNumState.value = phoneNumTemplate(digits)
},
modifier = modifier
.clip(RoundedCornerShape(16.dp))
.size(343.dp, 54.dp),
singleLine = true,
placeholder = {
Text(
"+7(___)_______", style = passwordTextStyle,
)
},
colors = TextFieldDefaults.textFieldColors(
backgroundColor = whiteBackground,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
cursorColor = greyColor,
textColor = greyColor
),
leadingIcon = {
Image(
painterResource(id = R.drawable.ic_phone),
stringResource(id = R.string.nomad_contentDescription_icon_phone)
)
},
keyboardOptions = KeyboardOptions(
imeAction = imeAction,
keyboardType = KeyboardType.Phone
),
)
}
String changer:
fun phoneNumTemplate(chars: List<Char>): String {
return if (chars.isNotEmpty()) {
val digits = mutableListOf<Int>()
chars.forEach {
digits.add(it.toString().toInt())
}
val template = StringBuilder()
digits.forEach { template.append(it) }
for (i in 0..11) {
template.append("_")
}
"+7(${template.substring(1, 4)}) ${template.substring(4,7)} ${template.substring(7,9)} ${template.substring(9, 11)}"
} else {
"+7(___) ___ __ __"
}
}
thank you for your help