Hey, lets create the OTP field today,
Use this Composable to create OTP
@Composable
fun OtpField(
modifier: Modifier = Modifier,
otp: MutableState<String>,
onDone: () -> Unit = {}
) {
Column(
modifier = modifier.fillMaxWidth(),
) {
BasicTextField(
value = otp.value,
onValueChange = {
},if (it.toIntOrNull() != null || it.isEmpty())if (it.length <= 4) otp.value = it
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number,
imeAction = if (otp.value.length == 4) ImeAction.Done else ImeAction.Next
),
keyboardActions = KeyboardActions(onDone = { onDone() })
) {
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = 20.dp),
horizontalArrangement = Arrangement.Absolute.SpaceBetween
) {
repeat(4) { index ->
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier
.padding(horizontal = 10.dp)
.border(
width = 1.dp,
color = Color.Black,
shape = RoundedCornerShape(30)
)
.height(50.dp)
.width(40.dp)
) {
Text(
text = if (index < otp.value.length) otp.value[index].toString() else "_",
)
}
}
}
}
}
}
Now to use this here is the use case
val otp = rememberSaveable {
mutableStateOf("")
}
OtpField(
otp = otp,
onDone = {
Toast.makeText(context, otp.value, Toast.LENGTH_SHORT).show()
}
)
Enjoy Your Day....
0 Comments