How do I get the currently displayed fragment?

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

    Sev's answer works for when you hit the back button or otherwise change the backstack.

    I did something slightly different, though. I have a backstack change listener setup on a base Fragment and its derived fragments and this code is in the listener:

    Fragment f = getActivity().getSupportFragmentManager().findFragmentById(R.id.container);
    
    if (f.getClass().equals(getClass())) {
        // On back button, or popBackStack(),
        // the fragment that's becoming visible executes here,
        // but not the one being popped, or others on the back stack
    
        // So, for my case, I can change action bar bg color per fragment
    }
    

提交回复
热议问题