'Is there a better way to implement this: __ __ __ ___ in jetpack
This is a textfield for inputting otp. Right now I have used boxes using outlined textfields but is there a way to do the small dashes that takes input instead? Code for inputting otp using outlined textfield
fun OTPTextFields( modifier: Modifier = Modifier, length: Int, onFilled: (code: String) -> Unit ) { var code: List by remember { mutableStateOf(listOf()) }
val focusRequesters: List<FocusRequester> = remember {
val temp = mutableListOf<FocusRequester>()
repeat(length) {
temp.add(FocusRequester())
}
temp
}
Row(
modifier = Modifier.height(55.dp)
) {
(0 until length).forEach { index ->
OutlinedTextField(
modifier = Modifier
.width(55.dp)
.height(55.dp)
.focusOrder(focusRequester = focusRequesters[index]) {
focusRequesters[index + 1].requestFocus()
},
textStyle = MaterialTheme.typography.caption.copy(
textAlign = TextAlign.Center, color = Color.Red,fontWeight = FontWeight.Bold,
), colors = TextFieldDefaults.outlinedTextFieldColors(
focusedBorderColor = Otpcolor,
unfocusedLabelColor = Otpcolor
),
singleLine = true,
value = code.getOrNull(index = index)?.takeIf {
it.isDigit()
}?.toString() ?: "",
onValueChange = { value: String ->
if (focusRequesters[index].freeFocus()) {
val temp = code.toMutableList()
if (value == "") {
if (temp.size > index) {
temp.removeAt(index = index)
code = temp
focusRequesters.getOrNull(index - 1)?.requestFocus()
}
} else {
if (code.size > index) {
temp[index] = value.getOrNull(0)?: ' '
} else {
temp.add(value.getOrNull(0) ?: ' ')
code = temp
focusRequesters.getOrNull(index + 1)?.requestFocus() ?: onFilled(
code.joinToString(separator = "")
)
}
}
}
},
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = KeyboardType.Number,
imeAction = ImeAction.Next
),
// visualTransformation = PasswordVisualTransformation()
)
Spacer(modifier = Modifier.width(15.dp))
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
