Is there a way to detect if focus is moving inside...
# compose
a
Is there a way to detect if focus is moving inside or outside of a group (ie a box)? If I set a
onFocusChanged {}
to the box and press tab to focus targets inside of a box, then the Box's onFocusChanged{} reports
hasFocused = false
for a split second.
l
What version of Compose are you using? There were some changes here recently
a
CMP 1.7.0
l
I think the changes will be in 1.8.0 then
Maybe you could try testing with a 1.8 beta build?
a
I can try, but what am i testing? what is the change?
l
We rewrote how requesting focus works, and how events are dispatched. So if the issue still reproduces, when using the latest version, maybe good to file a bug to track. I don’t know if it is intended that
hasFocused = false
shows up for a small period of time
Depends on what your hierarchy looks like too I guess
a
Behaves the same. When pressing tab to go from button 1 to button 2 i see 'group has focus false' and then true immediatelly
Copy code
Row(Modifier.fillMaxWidth().onFocusChanged { println("Group has focus ${it.hasFocus}") }) {
        Box(Modifier.clickable { }) {
            Text("Button 1")
        }
        Box(Modifier.clickable { }) {
            Text("Button 1")
        }
    }
l
I see, so I guess what is happening is that the ‘inactive’ comes from clearing focus from the first item, which notifies that item but also its parents. So the group basically sees that item 1 is now inactive, before item 2 becomes active
Actually, this is a bit weird since the focusChanged modifier kinda applies to both children. I think the typical expected usage is to add a
focusGroup()
modifier to the parent Row
Copy code
Row(Modifier.fillMaxWidth().onFocusChanged {
        println("Group has focus ${it.hasFocus}")
    }.focusGroup()) {
        Box(Modifier.clickable { }) {
            Text("Button 1")
        }
        Box(Modifier.clickable { }) {
            Text("Button 1")
        }
    }
This won’t print false, because the group never loses focus when moving between children
a
Nice. That seemed to do the trick. I tried this before but had the focusgroup before the onFocusChanged listener 🫠
thanks for the help Louis
l
Yeah, these focus modifiers basically ‘listen’ to, or affect the next focus target in the chain. Same with focusRequester, focusProperties, etc