【问题标题】:How to pop back stack when button is pressed on Jetpack Compose在Jetpack Compose上按下按钮时如何弹出堆栈
【发布时间】:2021-09-02 16:23:54
【问题描述】:

我在片段中有一个撰写屏幕,在该屏幕中有一个按钮。

我想在按下此按钮时关闭片段/返回上一个屏幕。

但我无法访问 onClick 中的任何活动/片段方法。

我该怎么做?

@AndroidEntryPoint
class MyFragment @Inject constructor() : Fragment(){

    @ExperimentalComposeUiApi
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
            this.setContent {
                Button(
                    onClick = {
                        //Dismiss fragment.
                    },
                ) {
                    Text(
                        "Click me"
                    )
                }
            }
        }
    }
}

【问题讨论】:

    标签: android kotlin android-jetpack-compose


    【解决方案1】:

    这样解决:

    @AndroidEntryPoint
    class MyFragment @Inject constructor(
    
    ) : Fragment(){
    
        @ExperimentalComposeUiApi
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View {
            return ComposeView(requireContext()).apply {
                this.setContent {
    
                    val shouldDismiss = remember { mutableStateOf(false) }
    
                    if (shouldDismiss) {
                        dismissFragment()
                    }else{
                        Button(
                            onClick = {
                                shouldDismiss.value = true
                            },
                        ) {
                            Text(
                                "Click me"
                            )
                        }
                    }
                }
            }
        }
    
        private fun dismissFragment(){
            activity?.onBackPressed()
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用LocalContext 获取任何可组合内容中的上下文。您可以从此获得活动,因此您可以使用onBackPressed() 或以其他方式导航:

      val context = LocalContext.current
      Button(
          onClick = {
              context.findActivity()?.onBackPressed()
          },
      ) {
          Text(
              "Click me"
          )
      }
      

      findActivity:

      fun Context.findActivity(): Activity? {
          var context = this
          while (context is ContextWrapper) {
              if (context is Activity) return context
              context = context.baseContext
          }
          return null
      }
      

      【讨论】:

        猜你喜欢
        • 2022-10-05
        • 1970-01-01
        • 2011-02-02
        • 2022-10-02
        • 2022-09-28
        • 2020-12-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多