How do I get the currently displayed fragment?

前端 未结 30 1735
青春惊慌失措
青春惊慌失措 2020-11-22 11:21

I am playing with fragments in Android.

I know I can change a fragment by using the following code:

FragmentManager fragMgr = getSupportFragmentManag         


        
相关标签:
30条回答
  • 2020-11-22 11:35

    I found findFragmentByTag isn't that convenient. If you have String currentFragmentTag in your Activity or parent Fragment, you need to save it in onSaveInstanceState and restore it in onCreate. Even if you do so, when the Activity recreated, onAttachFragment will called before onCreate, so you can't use currentFragmentTag in onAttachFragment(eg. update some views based on currentFragmentTag), because it's might not yet restored.

    I use the following code:

    Fragment getCurrentFragment() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if(fragments.isEmpty()) {
            return null;
        }
        return fragments.get(fragments.size()-1);
    }
    

    The document of FragmentManager state that

    The order of the fragments in the list is the order in which they were added or attached.

    When you need to do stuff based on current fragment type, just use getCurrentFragment() instance of MyFragment instead of currentFragmentTag.equals("my_fragment_tag").

    Note that getCurrentFragment() in onAttachFragment will not get the attaching Fragment, but the previous attached one.

    0 讨论(0)
  • 2020-11-22 11:38

    Kotlin way;

    val currentFragment = supportFragmentManager.fragments.last()
    
    0 讨论(0)
  • 2020-11-22 11:39

    When you add the fragment in your transaction you should use a tag.

    fragTrans.replace(android.R.id.content, myFragment, "MY_FRAGMENT");
    

    ...and later if you want to check if the fragment is visible:

    MyFragment myFragment = (MyFragment)getSupportFragmentManager().findFragmentByTag("MY_FRAGMENT");
    if (myFragment != null && myFragment.isVisible()) {
       // add your code here
    }
    

    See also http://developer.android.com/reference/android/app/Fragment.html

    0 讨论(0)
  • 2020-11-22 11:39

    Easy way to do that :

    Fragment fr=getSupportFragmentManager().findFragmentById(R.id.fragment_container);
    String fragmentName = fr.getClass().getSimpleName();
    
    0 讨论(0)
  • 2020-11-22 11:39

    I had to do this very recently and none of the answers here really suited this scenario.

    If you are confident that only one fragment will be visible (full-screen), so really want to find what's at the top of the backstack. For instance, as a Kotlin for Fragment:

    import androidx.fragment.app.Fragment
    
    fun Fragment.setVisibilityChangeListener(clazz: Class<out Fragment>, listener: (Boolean) -> Unit) {
        fragmentManager?.run {
            addOnBackStackChangedListener {
                val topFragmentTag = getBackStackEntryAt(backStackEntryCount - 1).name
                val topFragment = findFragmentByTag(topFragmentTag)
                listener(topFragment != null && topFragment::class.java == clazz)
            }
        }
    }
    

    And use it like:

    class MyFragment: Fragment {
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
    
            setVisibilityChangeListener(this::class.java) { visible -> 
                // Do stuff
            }
        }
    }
    
    0 讨论(0)
  • 2020-11-22 11:40

    Here is my solution which I find handy for low fragment scenarios

    public Fragment getVisibleFragment(){
        FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        if(fragments != null){
            for(Fragment fragment : fragments){
                if(fragment != null && fragment.isVisible())
                    return fragment;
            }
        }
        return null;
    }
    
    0 讨论(0)
提交回复
热议问题