How do I get the currently displayed fragment?

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

    I know it's an old post, but was having trouble with it previously too. Found a solution which was to do this in the onBackStackChanged() listening function

      @Override
        public void onBackPressed() {
            super.onBackPressed();
    
             Fragment f = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
          if(f instanceof CustomFragmentClass) 
            // do something with f
            ((CustomFragmentClass) f).doSomething();
    
        }
    

    This worked for me as I didn't want to iterate through every fragment I have to find one that is visible. Hope it helps someone else too.

提交回复
热议问题