get the latest fragment in backstack

后端 未结 17 2042
长发绾君心
长发绾君心 2020-11-27 11:24

How can I get the latest fragment instance added in backstack (if I do not know the fragment tag & id)?

FragmentManager fragManager = activity.getSupport         


        
相关标签:
17条回答
  • 2020-11-27 11:49

    If you use addToBackStack(), you can use following code.

    List<Fragment> fragments = fragmentManager.getFragments(); activeFragment = fragments.get(fragments.size() - 1);

    0 讨论(0)
  • 2020-11-27 11:53

    I will add something to Deepak Goel's answer since a lot of people, me included, were getting a null by using his method. Apparently to make the tag work when you add a fragment to the backstack you should be doing it like this:

    getSupportFragmentManager.beginTransaction().replace(R.id.container_id,FragmentName,TAG_NAME).addToBackStack(TAG_NAME).commit();
    

    You need to add the same tag twice.

    I would have commented but i don't have 50 reputation.

    0 讨论(0)
  • 2020-11-27 11:54

    Just took @roghayeh hosseini (correct) answer and made it in Kotlin for those here in 2017 :)

    fun getTopFragment(): Fragment? {
        supportFragmentManager.run {
            return when (backStackEntryCount) {
                0 -> null
                else -> findFragmentByTag(getBackStackEntryAt(backStackEntryCount - 1).name)
            }
        }
    }
    

    *This should be called from inside an Activity.

    Enjoy :)

    0 讨论(0)
  • 2020-11-27 11:55

    Or you may just add a tag when adding fragments corresponding to their content and use simple static String field (also you may save it in activity instance bundle in onSaveInstanceState(Bundle) method) to hold last added fragment tag and get this fragment byTag() at any time you need...

    0 讨论(0)
  • 2020-11-27 11:58

    The highest (Deepak Goel) answer didn't work well for me. Somehow the tag wasn't added properly.

    I ended up just sending the ID of the fragment through the flow (using intents) and retrieving it directly from fragment manager.

    0 讨论(0)
  • 2020-11-27 11:58

    Kotlin Developers can use this to get the current fragment:

            supportFragmentManager.addOnBackStackChangedListener {
            val myFragment = supportFragmentManager.fragments.last()
    
            if (null != myFragment && myFragment is HomeFragment) {
                //HomeFragment is visible or currently loaded
            } else {
                //your code
            }
        }
    
    0 讨论(0)
提交回复
热议问题