How do I get the currently displayed fragment?

前端 未结 30 2117
青春惊慌失措
青春惊慌失措 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:34

    If get here and you are using Kotlin:

    var fragment = supportFragmentManager.findFragmentById(R.id.fragment_container)
    

    R.id.fragment_container is the id where the fragment is presenting on their activity

    Or if you want a nicer solution:

    supportFragmentManager.findFragmentById(R.id.content_main)?.let {
        // the fragment exists
    
        if (it is FooFragment) {
            // The presented fragment is FooFragment type
        }
    }
    

提交回复
热议问题