如何在浏览器中打开链接如果我单击按钮。我正在使用Compose for Desktop。
Button(onClick = {
// What I have to write here..
}) {
Text(
text = "Open a link",
color = Color.Black
)
}
提前谢谢。
使用Desktop#浏览(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
)
}
最小示例
- 将函数代码放入commonMain模块
expect fun browseUrl(url: String)
- 将功能代码放入desktopMain模块
actual fun browseUrl(url: String) {
val desktop = Desktop.getDesktop()
desktop.browse(URI.create(url))
}
- 使用
onClick = {
browseUrl("http://${link}")
}