rsktash
08/27/2021, 5:40 PMRalston Da Silva
08/27/2021, 6:36 PMrsktash
08/27/2021, 6:45 PMRalston Da Silva
08/27/2021, 7:07 PM@Composable
fun TestFocusWithDynamicContent() {
val list = remember { mutableStateListOf("") }
val focusRequesters = list.indices.map { remember(it) { FocusRequester() } }
Column {
list.forEachIndexed { index, item ->
if (index != list.lastIndex) {
OutlinedTextField(
value = item,
onValueChange = {
list[index] = it
if (index == list.lastIndex && it.isNotEmpty()) list.add("")
},
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequesters[index])
.relocate("$index"),
placeholder = { Text(text = "type anything") }
)
}
else {
OutlinedTextField(
value = "",
onValueChange = {
if (index == list.lastIndex && it.isNotEmpty()) list.add("")
}
)
}
}
}
}
Moving the index check to the onValue changed solves this issue:
@Composable
fun TestFocusWithDynamicContent() {
val list = remember { mutableStateListOf("") }
Column {
list.forEachIndexed { index, item ->
OutlinedTextField(
value = item,
onValueChange = {
if (index == list.lastIndex && it.isNotEmpty()) {
list.add("")
} else {
list[index] = it
}
},
modifier = Modifier
.fillMaxWidth()
.relocate("$index"),
placeholder = { Text(text = "type anything") }
)
}
}
}
rsktash
08/27/2021, 7:15 PMRalston Da Silva
08/27/2021, 9:27 PMrsktash
08/27/2021, 9:30 PMRalston Da Silva
08/27/2021, 9:39 PM@Composable
private fun ComposeItem(
item: String,
isLastItem: Boolean,
onValueChange: (String) -> Unit,
addNew: (String) -> Unit,
focusRequester: FocusRequester
) {
if (!isLastItem) {
OutlinedTextField(
value = item,
onValueChange = {
onValueChange(it)
},
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
placeholder = { Text(text = "type anything") }
)
} else {
OutlinedTextField(
value = "",
onValueChange = {
onValueChange(it)
if (it.isNotEmpty()) {
Log.d("ComposeItem", "onValueChange: $it")
addNew("")
}
},
placeholder = { Text(text = "type new item") }
)
}
}
Let's assume the last index is 3
In this function you create TextField in the else block. When that text field has focus, you add a new item to the list.
Now, when this is recomposed, index 3 is not the last index, so you create a new TextField in the if block.
This newly created TextField does not have focus.rsktash
08/27/2021, 9:54 PMRalston Da Silva
08/27/2021, 9:57 PMrsktash
08/27/2021, 9:58 PMRalston Da Silva
08/27/2021, 9:58 PMrsktash
08/27/2021, 9:59 PMRalston Da Silva
08/27/2021, 10:10 PMrsktash
08/27/2021, 10:12 PMAnimatedInsetState
where we can pass to enqueue actionsRalston Da Silva
08/27/2021, 10:14 PMrsktash
08/27/2021, 10:14 PMRalston Da Silva
08/27/2021, 10:15 PM