How do I programmatically open an external url on button click with jetpack compose?

Viewed 5205

How do I programmatically open an external url on button click with jetpack compose?

    @Composable
    fun MyButton() {
     Button(onClick = {
    //enter code here
    })
}
4 Answers

An easier alternative is to use LocalUriHandler:

val uriHandler = LocalUriHandler.current
uriHandler.openUri(uri)

Keep it short and sweet

Here is a possible way to do it:

@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!")
    }
}

Inside @Composable functions, you have one thing called "Composition Locals".

CompositionLocal classes allow passing data implicitly through composable functions to its composable descendants

LocalContext is one of these classes. The Intent specified, is the common way to open an external URL on Android.

I've been using CustomTabsIntent which is another possibility when it comes to open a link in the phone browser.

// 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))
           }

@Composable fun 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",
        )
}

}

Related