https://kotlinlang.org logo
Title
r

ritesh

04/08/2022, 8:12 AM
Probably a very basic question. More in 🧵
BOX
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
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

f.babic

04/08/2022, 8:17 AM
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

ritesh

04/08/2022, 8:21 AM
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

f.babic

04/08/2022, 8:25 AM
I imagine there are internal handles that might be overriden when you add focusable to the TextField.
r

ritesh

04/08/2022, 8:26 AM
yeah, that could be the reason. Thanks!