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

Tom Truyen

11/11/2023, 4:24 PM
Hi, I am working on an AutoCompleteTextView/ExposedDropdownMenuBox in Jetpack compose for Desktop. For some reason with my current implementation whenever I get a lot of items from my API returned the DropdownMenu overlaps with my TextField, how can I prevent this behaviour? I have already tried to calculate the height of the screen and subtract the TextField height but without much success
Copy code
@Composable
fun TextFieldWithDropdown(
    modifier: Modifier = Modifier,
    value: String,
    onValueChange: (String) -> Unit,
    options: List<String>,
    onOptionClick: (String) -> Unit,
) {
    val density = LocalDensity.current

    var text by remember {
        mutableStateOf(value)
    }

    var expanded by remember(options) { mutableStateOf(options.isNotEmpty()) }

    var anchorSize by remember {
        mutableStateOf(DpSize.Zero)
    }

    Box(modifier) {
        TextField(
            modifier = Modifier
                .fillMaxWidth()
                .onGloballyPositioned {
                    anchorSize = with(density) {
                        DpSize(
                            width = it.size.width.toDp(),
                            height = it.size.height.toDp()
                        )
                    }
                }
                .onFocusChanged { focusState ->
                    if (!focusState.isFocused) {
                        expanded = false
                    }
                },
            singleLine = true,
            value = text,
            onValueChange = {
                text = it
                onValueChange(it)
            },
            colors = TextFieldDefaults.textFieldColors(
                backgroundColor = MaterialTheme.colors.surface,
                textColor = MaterialTheme.colors.onSurface,
                cursorColor = MaterialTheme.colors.onSurface,
            ),
        )


        DropdownMenu(
            modifier = Modifier
                .width(anchorSize.width),
            offset = DpOffset(0.dp, Dimens.normal),
            focusable = false,
            expanded = expanded,
            onDismissRequest = { expanded = false }
        ) {
            options.forEach { text ->
                DropdownMenuItem(
                    onClick = {
                        onOptionClick(text)
                    }
                ) {
                    Text(text = text)
                }
            }
        }
    }
}
k

Kirill Grouchnikov

11/11/2023, 6:29 PM
You already have a discussion in the desktop channel, no need to flood multiple channels
z

Zach Klippenstein (he/him) [MOD]

11/12/2023, 12:32 AM
And please keep long code snippets to the thread, thanks!
t

Tom Truyen

11/13/2023, 5:50 PM
My apologies. I made this before I saw that there was a channel for desktop only. I will keep long code snippets in threads in the future!
gratitude thank you 1
3 Views