Probably a very basic question. More in :thread:
# compose
r
Probably a very basic question. More in 🧵
BOX
Copy code
Box(
    Modifier
        .clickable { focusRequester.requestFocus() }
        .border(2.dp, color)
        // The focusRequester should be added BEFORE the focusable.
        .focusRequester(focusRequester)
        // The onFocusChanged should be added BEFORE the focusable that is being observed.
        .onFocusChanged { color = if (it.isFocused) Green else Black }
        .focusable()
){
    Text(text = "Box")
}

LaunchedEffect(Unit) {
    focusRequester.requestFocus()
}
TextField
Copy code
val focusRequester = remember { FocusRequester() }
    TextField(
        value = value, 
        onValueChange = { value = it },
        modifier = Modifier.focusRequester(focusRequester)
    )
    
    LaunchedEffect(Unit) {
        focusRequester.requestFocus()
    }
Why
Box
needs
.focusable
for the
focusRequester
to work and
TextField
doesn't. If i give
.focusable
to TextFiled and not to the Box, focusRequester doesn't work.
f
Without diving into it - I imagine it's because the
TextField
can be focusable by default, whereas a Box cannot. So requesting focus on an element that can't be focused (Box w/o
focusable()
) doesn't work, but requesting it on
TextField
, which is
focusable()
by default does.
r
yeah, my initial understanding was same, i was hoping if composable like
TextField
are
focusable
by default, giving
.focusable
to it's modifier should not have any effect, as in
focusRequester
should have worked irrespective of marking it focusable or not. Not, sure if it makes sense.
f
I imagine there are internal handles that might be overriden when you add focusable to the TextField.
r
yeah, that could be the reason. Thanks!