我正在尝试使用 Jetpack compose 重写我的项目 UI。在android中使用jetpack compose添加弹出菜单有什么想法吗?
like this one

我尝试使用 Stack() 布局来实现它,但结果不符合标准。

@Composable
fun LiveDataComponentList(productList: List<Product>) {
    AdapterList(data = productList) { product ->
        Stack() {
            Clickable(onClick = { PopupState.toggleOwner(product) }) {
                Card(...) {...}

            if (PopupState.owner == product) {
                Surface(color = Color.Gray,modifier = Modifier.gravity(Alignment.TopEnd) + Modifier.padding(12.dp)) {
                    Column() {
                        Text("menu 1")
                        Text("menu 2")
                        Text("menu 3")
                        Text("menu 4")
                        Text("menu 5")
                    }
                }
            }
        }
    }
}

和 PopupState 是
@Model
object PopupState
{
    var owner:Product?=null
    fun toggleOwner(item:Product)
    {
        if(owner==item)
            owner=null
        else
            owner=item
    }
}

结果是

screenshot

最佳答案

由于删除了 DropDownPopup,我使用 DropDownMenu 实现了一个,而不是这样的:
弹出菜单:

@Composable
fun PopupMenu(
    menuItems: List<String>,
    onClickCallbacks: List<() -> Unit>,
    showMenu: Boolean,
    onDismiss: () -> Unit,
    toggle: @Composable () -> Unit,
) {
    DropdownMenu(
        toggle = toggle,
        expanded = showMenu,
        onDismissRequest = { onDismiss() },
    ) {
        menuItems.forEachIndexed { index, item ->
            DropdownMenuItem(onClick = {
                onDismiss()
                onClickCallbacks[index]
            }) {
                Text(text = item)
            }
        }
    }
}
切换(长按触发 PopupMenu 的东西):
@Preview
@Composable
fun Toggle() {
    var showMenu by remember { mutableStateOf(false) }

    PopupMenu(
        menuItems = listOf("Delete"),
        onClickCallbacks = listOf { println("Deleted") },
        showMenu = showMenu,
        onDismiss = { showMenu = false }) {
        Text(
            modifier = Modifier.clickable(onClick = {}, onLongClick = {
                showMenu = true
            }),
            text = "Long click here",
        )
    }
}

关于android - Jetpack 撰写弹出菜单,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61630838/

10-11 20:10