kotlin - 如何在 jetpack compose desktop 上制作两个窗口并从一个窗口转到另一个窗口?

例如,当我单击按钮时,如何在 jetpack compose desktop 上制作两个窗口并从一个窗口转到另一个窗口?

fun main() = application {
    Window(
        onCloseRequest = ::exitApplication,
        title = "Products Manager",
        state = rememberWindowState(width = 700.dp, height = 600.dp)
    ) {
        val count = remember { mutableStateOf(0) }
        MaterialTheme {
            Column(Modifier.fillMaxSize(), Arrangement.spacedBy(5.dp)) {
                Button(modifier = Modifier.align(Alignment.CenterHorizontally),
                    onClick = {
                        count.value++
                    }) {
                    Text(if (count.value == 0) "Hello World" else "Clicked ${count.value}!")
                }
                Button(modifier = Modifier.align(Alignment.CenterHorizontally),
                    onClick = {
                        count.value = 0
                    }) {
                    Text("Reset")
                }
            }
        }
    }
}

回答1

要创建多个窗口,您只需要拥有多个 Window 可组合项。例如,查看 https://github.com/JetBrains/compose-jb/tree/master/tutorials/Window_API_new#open-and-close-multiple-windows 文档部分。

要以编程方式在窗口之间切换,您可以在应该成为最顶层的窗口上使用 window.toFront()windowWindow.content 内的 FrameWindowScope 中可用的属性。

这是一个如何使用两种窗口“类型”来完成的示例。您可以将 type 替换为任何其他标识符。

enum class WindowTypes {
    First,
    Second,
}

fun main() = application {
    val windowFocusRequestSharedFlow = remember { MutableSharedFlow<WindowTypes>() }

    WindowTypes.values().forEach { windowType ->
        key(windowType) {
            Window(
                title = windowType.toString(),
                onCloseRequest = ::exitApplication,
            ) {
                LaunchedEffect(Unit) {
                    windowFocusRequestSharedFlow
                        .filter { it == windowType }
                        .collect {
                            window.toFront()
                        }
                }
                val scope = rememberCoroutineScope()
                Button({
                    scope.launch {
                        val windowTypeToFocus = WindowTypes.values().run {
                            get((indexOf(windowType) + 1) % count())
                        }
                        windowFocusRequestSharedFlow.emit(windowTypeToFocus)
                    }
                }) {
                    Text("next window")
                }
            }
        }
    }
}

相似文章