如果单击按钮,如何在浏览器中打开链接。我正在为此使用Compose for Desktop。
Button(onClick = {
// What I have to write here..
}) {
Text(
text = "Open a link",
color = Color.Black
)
}
提前致谢。
如果单击按钮,如何在浏览器中打开链接。我正在为此使用Compose for Desktop。
Button(onClick = {
// What I have to write here..
}) {
Text(
text = "Open a link",
color = Color.Black
)
}
提前致谢。
使用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;
}
受https://stackoverflow.com/a/54869038/1575096的启发,也可以在 Linux 和 Mac 上工作:
fun openInBrowser(uri: URI) {
val osName by lazy(LazyThreadSafetyMode.NONE) { System.getProperty("os.name").lowercase(Locale.getDefault()) }
val desktop = Desktop.getDesktop()
when {
Desktop.isDesktopSupported() && desktop.isSupported(Desktop.Action.BROWSE) -> desktop.browse(uri)
"mac" in osName -> Runtime.getRuntime().exec("open $uri")
"nix" in osName || "nux" in osName -> Runtime.getRuntime().exec("xdg-open $uri")
else -> throw RuntimeException("cannot open $uri")
}
}
Button(onClick = { openInBrowser(URI("https://domain.tld/page")) }) {
Text(
text = "Open a link",
color = Color.Black
)
}