【发布时间】:2021-03-25 14:41:16
【问题描述】:
如何使用 jetpack compose 以编程方式在按钮单击时打开外部 url?
@Composable
fun MyButton() {
Button(onClick = {
//enter code here
})
}
【问题讨论】:
标签: android kotlin onclick android-jetpack-compose
如何使用 jetpack compose 以编程方式在按钮单击时打开外部 url?
@Composable
fun MyButton() {
Button(onClick = {
//enter code here
})
}
【问题讨论】:
标签: android kotlin onclick android-jetpack-compose
更简单的替代方法是使用LocalUriHandler:
val uriHandler = LocalUriHandler.current
uriHandler.openUri(uri)
保持简短和甜蜜?
【讨论】:
这是一种可能的方法:
@Composable
fun MyButton() {
val context = LocalContext.current
val intent = remember { Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com/")) }
Button(onClick = { context.startActivity(intent) }) {
Text(text = "Navigate to Google!")
}
}
在@Composable 函数中,有一个东西叫做"Composition Locals"。
CompositionLocal 类允许通过可组合函数将数据隐式传递给它的可组合后代
LocalContext 是这些类之一。 指定的 Intent 是在 Android 上打开外部 URL 的常用方式。
【讨论】:
我一直在使用 CustomTabsIntent,这是在手机浏览器中打开链接的另一种可能性。
// Within your @Composable function define the context val
val context = LocalContext.current
//Then in your modifier clickable use the CustomTabsIntent builder
modifier = Modifier
.padding(start = 24.dp, end = 16.dp)
.align(Alignment.CenterVertically)
.clickable {
CustomTabsIntent.Builder().build().launchUrl(context, Uri.parse(pageUrl))
}
【讨论】:
@可组合 有趣的 WebButton() {
val context = LocalContext.current
val webIntent: Intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com/"))
OutlinedButton(onClick = { context.startActivity(webIntent) }, modifier = Modifier.padding(8.dp)) {
Text( text = "OPEN WEB",
)
}
}
【讨论】: