Florian

    Florian

    11 months ago
    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 ->
    @Csaba Kozák what do you mean by the thread icon reaction? Do you mean I should put the code inside a thread?
    Csaba Kozák

    Csaba Kozák

    11 months ago
    Florian

    Florian

    11 months ago
    ok sorry
    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()
                }
            }
        }
    }
    Csaba Kozák

    Csaba Kozák

    11 months ago
    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
    .
    Florian

    Florian

    11 months ago
    @Csaba Kozák yep that's what I ended up doing 👍
    thank you