简体   繁体   English

如何从 DialogFragment 获取 backstack 中的顶部 Fragment

[英]How to get top Fragment in backstack from DialogFragment

I'm using navigation to navigate between fragments.我正在使用导航在片段之间导航。

And I have a DialogFragment, it can called from from many fragment like this:我有一个 DialogFragment,它可以从许多片段中调用,如下所示:

 val dialog = FragmentDialog
 dialog.show(childFragmentManager, "home_fragment")

And I want to know dialogfragment called by which fragment我想知道哪个片段调用了对话片段

I tried with FragmentManager.backStackEntryCount but it's seem doesn't work我尝试使用FragmentManager.backStackEntryCount但它似乎不起作用

Can I have a advice for this problem???我可以为这个问题提供建议吗???

can you explain why you need to know dialogfragment called by which fragment你能解释一下为什么你需要知道哪个片段调用的dialogfragment

 fun showInAppDialog() {
        val mInAppFragment: InAppScreenFragmentDialog = 
        InAppScreenFragmentDialog.instance
        supportFragmentManager.beginTransaction().add(mInAppFragment, 
        "IN_APP_DIALOG")
        .commitAllowingStateLoss()
    
    }

  private fun dismissInAppDialog() {
        if (isFinishing) return
        val manager: FragmentManager = supportFragmentManager
        val mInAppFragment: InAppScreenFragmentDialog? =
            manager.findFragmentByTag("IN_APP_DIALOG") as InAppScreenFragmentDialog?
        if (mInAppFragment!= null) {
            supportFragmentManager.beginTransaction().remove(mInAppFragment).commitAllowingStateLoss()
        }
}

There are multiple ways to do this..有多种方法可以做到这一点..

  1. You can just Pass a key in Bundle to your DialogFragment to check which Fragment opened it..您可以将Bundle中的一个键传递给您的DialogFragment以检查哪个 Fragment 打开了它。

  2. If your Dialog fragment a attached to a fragment in each case you can just use getParentFragment() .如果您的 Dialog 片段在每种情况下都附加到fragment ,则您可以使用getParentFragment() getParentFragment() will return the instance of that fragment. getParentFragment()将返回该片段的实例。 If its attached to activity then getParentFragment() will be null so watch out for this case also.如果它附加到活动,那么getParentFragment()将是 null 所以也要注意这种情况。

  3. you can also use getTag() from where it was open byt passing different tags to transaction.您还可以通过将不同的标签传递给事务来使用打开它的getTag()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM