How to open URL with an image?

197 views Asked by At

How do I open an external URL on a clickable image with Jetpack Compose?

Thanks !

@Composable
fun Replay() {
    Box(
        modifier = Modifier
    )
    Row (
        modifier = Modifier
            .padding(20.dp)
            .fillMaxWidth(),
        horizontalArrangement = Arrangement.Center
    ) {
            Image(
                painter = painterResource(id = R.drawable.logoreplay),
                contentDescription = "logoreplay",
                modifier = Modifier
                    .size(130.dp)
                    .padding(10.dp)
                    .clickable { 
                        
                    }
            )

I searched everywhere but didn't find the answer.

2

There are 2 answers

0
Tenfour04 On

Create an Intent for viewing the URL, then open it using the local Context.

.clickable { 
    val intent = Intent(Intent.ACTION_VIEW, Uri.parse(theUrlString))
    try {
        LocalContext.current.startActivity(intent)
    } catch (e: ActivityNotFoundException) {
        // log error or take some other action, but it would be very rare for a 
        // device to have no browser installed
    }
}
0
Prem Thakur On

Make the Image clickable by using the clickable modifier. In this, you can create an intent to open the link. Like this:

@Composable
fun Reply(url : String){
   //get the context from the compose context
   val context = LocalContext.current
    ...
    Image(
          ....
        modifier = Modifier
                     .clickable { 
       val intent = Intent(Intent.ACTION_VIEW, url.toUri())
       try {
           context.startActivity(intent)
        } catch (e: ActivityNotFoundException) {
           //use has no app installed to load this url
           //show an error msg, for eg, in a toast or something.
      }
   }
   )

}