kotlin 下拉菜单未正确显示

rta7y2nd  于 2023-03-13  发布在  Kotlin
关注(0)|答案(1)|浏览(172)

我正在做一个项目,我需要添加一个下拉菜单的问题是,当它出现在屏幕上的菜单是在屏幕的底部。
这是密码

@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,
                )
            }
        }

    }
}

这是屏幕上显示的样子
screen image
我尝试使用偏移量修改器,但仍然没有任何效果。

2nbm6dog

2nbm6dog1#

DropdownMenu放入具有同级的Box中,该同级将用作“锚点”。请注意,DropdownMenu本身不会占用布局中的任何空间,因为菜单显示在其他内容顶部的单独窗口中。

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

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

更好的解决方案是使用ExposedDropdownMenuBox,如answer中所述。

相关问题