How do I get the currently displayed fragment?

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

    There's a method called findFragmentById() in SupportFragmentManager. I use it in the activity container like :

    public Fragment currentFragment(){
        return getSupportFragmentManager().findFragmentById(R.id.activity_newsfeed_frame);
    }
    

    That's how to get your current Fragment. If you have custom Fragment and need to check what Fragment it is, I normally use instanceof :

    if (currentFragment() instanceof MyFrag){
        // Do something here
    }
    

提交回复
热议问题