1

Im doing an project and i need to add a dropdownMenu the problem is that when it appears on the screen the menu is at the bottom of the screen.

This is the code

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun QrCreatePhase1(navController: NavController){

    var expanded by remember { mutableStateOf(false) }
    val items = listOf("Option 1", "Option 2", "Option 3")
    var selectedItem by remember { mutableStateOf("") }
    val interactionSource = remember { MutableInteractionSource() }
    var textFiledSize by remember { mutableStateOf(Size.Zero) }

    val icon = if(expanded){
        Icons.Filled.KeyboardArrowUp
    }else{
        Icons.Filled.KeyboardArrowDown
    }

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
        modifier = Modifier
            .fillMaxWidth()
            .fillMaxHeight()
            .clip(RoundedCornerShape(topStart = 30.dp, topEnd = 30.dp))
            .padding(horizontal = 16.dp)
            .background(Color.White)
    ) {
        
        OutlinedTextField(
            value = selectedItem,
            readOnly = true,
            onValueChange = {selectedItem = it},
            modifier = Modifier
                .fillMaxWidth()
                .onGloballyPositioned { coordinates ->
                    textFiledSize = coordinates.size.toSize()
                },
            label = { Text(text = "Escolha um bloco")},
            trailingIcon = {
                Icon(icon, "", Modifier.clickable {expanded = !expanded})
            }
        )
        DropdownMenu(
            expanded = expanded,
            onDismissRequest = { expanded = false },
            modifier = Modifier
                .width(with(LocalDensity.current){textFiledSize.width.toDp()})
                .offset(y = with(LocalDensity.current) { textFiledSize.height.toDp() })
        ) {
            items.forEach { label ->
                DropdownMenuItem(
                    text = { Text(text = label)},
                    onClick = { selectedItem = label },
                    contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding,
                )
            }
        }

    }
}

and this is what looks like on the screen

screen image

What i tried is using the offset modifier and still did nothing.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841

1 Answers1

0

Place the DropdownMenu in a Box with a sibling that will be used as the 'anchor'. Note that a DropdownMenu by itself will not take up any space in a layout, as the menu is displayed in a separate window, on top of other content.

Column(
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Arrangement.Center
) {

    Box(){
         OutlinedTextField()
         DropdownMenu()
    }
}

enter image description here

A better solution is to use a ExposedDropdownMenuBox as described in this answer.

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841