https://kotlinlang.org logo
n

Nipun Rajput

11/05/2020, 8:28 AM
Hello folks, I'm creating OTP view and the problem is cursor is not moving to the next box when entering otp in to the boxes, I'm using focusrequester with each textfield and on value change i am calling focus requester of next box but it is giving me a crash. Please check the code below and suggest if there can be any other way in compose to achieve this.
Copy code
val textStateList = remember { mutableStateListOf<MutableState<TextFieldValue>>() }
val focusRequesters = List(4) { FocusRequester() }

Row(
    modifier = Modifier
        .fillMaxWidth()
        .padding(start = 15.dp, end = 15.dp)
        .align(Alignment.CenterHorizontally)
) {
    for (i in 0..3) {
        key(i) {
            val textState = mutableStateOf(TextFieldValue(""))
            textStateList.add(textState)

            OTPTextBox(
                modifier = Modifier.weight(1F).align(Alignment.CenterVertically),
                textState = textState,
                if (i == 3) ImeAction.Done else ImeAction.Next,
                focusRequesters[i],
                if (i > 0) focusRequesters[i - 1] else null,
                if (i < 3) focusRequesters[i + 1] else null
            )
            if (i < 3)
                Spacer(modifier = Modifier.width(15.dp))
        }
    }
}
For OTPTextBox
Copy code
TextField(
    value = textState.value,
    onValueChange = { newValue ->
        nextFocusRequester?.requestFocus()
        textState.value = newValue
    },
    modifier = modifier
        .fillMaxWidth()
        .border(width = 1.dp, color = offWhite, shape = RoundedCornerShape(10.dp))
        .focusRequester(focusRequester)
        .padding(24.dp))