How do I get the currently displayed fragment?

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

    Inspired by Tainy's answer, here is my two cents. Little modified from most other implementations.

    private Fragment getCurrentFragment() {
        FragmentManager fragmentManager = myActivity.getSupportFragmentManager();
        int stackCount = fragmentManager.getBackStackEntryCount();
        if( fragmentManager.getFragments() != null ) return fragmentManager.getFragments().get( stackCount > 0 ? stackCount-1 : stackCount );
        else return null;
    }
    

    Replace "myActivity" with "this" if it is your current activity or use reference to your activity.

提交回复
热议问题