https://kotlinlang.org logo
#compose
Title
# compose
f

Florian

10/14/2021, 8:47 AM
My search field requests focus when it's opened and I wanna close it when it loses focus. The problem is that there is a race condition so that it opens and then closes right away. Any idea how to fix this? Code see Thread ->
🧵 3
@Csaba Kozák what do you mean by the thread icon reaction? Do you mean I should put the code inside a thread?
c

Csaba Kozák

10/14/2021, 9:04 AM
f

Florian

10/14/2021, 9:08 AM
ok sorry
Code:
Copy code
@Composable
fun ExpandableSearchTextField(
    expanded: Boolean,
    onSearchIconClicked: () -> Unit,
    searchInput: String,
    onSearchInputChange: (String) -> Unit,
    onFocusLost: () -> Unit,
    modifier: Modifier = Modifier,
) {
    val focusRequester = remember { FocusRequester() }

    Box(modifier) {
        if (!expanded) {
            IconButton(onClick = onSearchIconClicked) {
                Icon(
                    imageVector = Icons.Default.Search,
                    contentDescription = stringResource(R.string.search),
                )
            }
        } else {
            val tint = LocalContentColor.current.copy(LocalContentAlpha.current)
            TextField(
                value = searchInput,
                onValueChange = onSearchInputChange,
                colors = TextFieldDefaults.textFieldColors(
                    focusedIndicatorColor = Color.Transparent,
                    unfocusedIndicatorColor = Color.Transparent,
                    backgroundColor = Color.Transparent,
                    cursorColor = tint
                ),
                placeholder = {
                    Text(
                        stringResource(R.string.search_field_hint),
                        color = tint
                    )
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .focusRequester(focusRequester)
                    .onFocusChanged { focusState ->
                        if (!focusState.isFocused) {
                            onFocusLost()
                        }
                    }
            )
            SideEffect {
                focusRequester.requestFocus()
            }
        }
    }
}
c

Csaba Kozák

10/14/2021, 9:11 AM
I think you have to create a
remember { mutableStateOf(false) }
to track wether the text field was opened before, and if not, do not close it when a focus changed is triggered. Of course, you have to update this
var
.
f

Florian

10/14/2021, 9:20 AM
@Csaba Kozák yep that's what I ended up doing 👍
👍 1
thank you