首页 > 解决方案 > 使用 Compose for Desktop 在浏览器中打开链接

问题描述

如果单击按钮,如何在浏览器中打开链接。我正在为此使用Compose for Desktop

Button(onClick = {
    // What I have to write here..
}) {
    Text(
        text = "Open a link",
        color = Color.Black
    )
}

提前致谢。

标签: kotlincompose-desktop

解决方案


使用Desktop#browse(URI)方法。它在用户的默认浏览器中打开一个 URI。

public static boolean openWebpage(URI uri) {
    Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
    if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
        try {
            desktop.browse(uri);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return false;
}

public static boolean openWebpage(URL url) {
    try {
        return openWebpage(url.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    return false;
}

推荐阅读