How to determine where focus went after my TextField lost focus (Android Jetpack Compose)

Viewed 935

When my TextField lost focus how can I determine where focus went?

var input1 by remember { mutableStateOf("") }
var input2 by remember { mutableStateOf("") }

Column{
    TextField(
        value = input1,
        onValueChange = {input1=it},
        Modifier.width(150.dp).onFocusChanged { state ->
            if (state == FocusState.Inactive){
                // Here I know that Input1 lost focus but how can I determine for sure the focus went to other then Input2 UI element?
                if (focusWentNotToInput2){
                       // Do semething
                }
            }
        }
    )
    TextField(
        value = input2,
        onValueChange = {input2=it},
        Modifier.width(150.dp)
    )
}
1 Answers

I found a solution for this but not like it 100%. At least it works. I am setting a flag if input2 is focused then if input1 loses focus I wait for 50ms and if isInput2Focused flag is not triggered then some other ui element is focused

var isInput2Focused by remember { mutableStateOf(false)}

var input1 by remember { mutableStateOf("") }
var input2 by remember { mutableStateOf("") }

val coroutineScope = rememberCoroutineScope()

Column{
    TextField(
        value = input1,
        onValueChange = {input1=it},
        Modifier.width(150.dp).onFocusChanged { state ->
            if (state.isFocused) isInput2Focused = false
            else{
                coroutineScope.launch {
                  delay(50)
                  if (!isInput2Focused){
                       // Do semething
                  }
                }
            }
        }
    )
    TextField(
        value = input2,
        onValueChange = {input2=it},
        Modifier.width(150.dp).onFocusChanged { state ->
            if (state.isFocused) isInput2Focused = true
        }
    )
}
Related