【问题标题】:How do I programmatically open an external url on button click with jetpack compose?如何使用 jetpack compose 以编程方式在按钮单击时打开外部 url?
【发布时间】:2021-03-25 14:41:16
【问题描述】:

如何使用 jetpack compose 以编程方式在按钮单击时打开外部 url?

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

【问题讨论】:

    标签: android kotlin onclick android-jetpack-compose


    【解决方案1】:

    更简单的替代方法是使用LocalUriHandler

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

    保持简短和甜蜜?

    【讨论】:

      【解决方案2】:

      这是一种可能的方法:

      @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 的常用方式。

      【讨论】:

      • 非常感谢,我试试看。
      • 工作得很好!再次感谢
      • 很高兴听到这个消息!
      【解决方案3】:

      我一直在使用 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))
                 }
      

      【讨论】:

        【解决方案4】:

        @可组合 有趣的 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",
                )
        }
        

        }

        【讨论】:

          猜你喜欢
          • 2022-06-23
          • 1970-01-01
          • 1970-01-01
          • 2021-12-19
          • 2022-09-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多