0

I am adding fragments in AppCompatActivity. And I want to know when any fragment get focus or lost focus. E.g When new fragment added, then I want some code tells to previous fragment i.e. he lost focus.

I have already tried setUserVisibleHint() and onHiddenChanged() methods but both are not working.

Can someone tell me how to do this.

Mca Dc
  • 11
  • 6
  • is it technically possible to focus multiple fragments at once? try logging each fragments onResume and onPause. i assume your fragments are focus between these two lifecycle events. – Daniel Bo Sep 07 '15 at 09:52
  • @DanielBo The fragments onResume() or onPause() will be called only when the Activities onResume() or onPause() is called. See here: http://stackoverflow.com/questions/11326155/fragment-onresume-onpause-is-not-called-on-backstack#16252923 – Mca Dc Sep 07 '15 at 10:16
  • 1
    See my answer it is working for me. – Mca Dc Sep 07 '15 at 10:17
  • thats why i asked you to log the fragments onResume and onPause, and not the activities. – Daniel Bo Sep 07 '15 at 10:18

1 Answers1

0

Thanks to @oriharel for a nice workaround to handle this case. Here is code:

In your activity (MyActivity), add this listener:

getSupportFragmentManager().addOnBackStackChangedListener(getListener());

(As you can see I'm using the compatibility package).

getListener implementation:

private OnBackStackChangedListener getListener()
{
    OnBackStackChangedListener result = new OnBackStackChangedListener()
    {
        public void onBackStackChanged() 
        {                   
            FragmentManager manager = getSupportFragmentManager();

            if (manager != null)
            {
                MyFragment currFrag = (MyFragment)manager.
                findFragmentById(R.id.fragmentItem);

                currFrag.onFragmentResume();
            }                   
        }
    };

    return result;
}

MyFragment.onFragmentResume() will be called after a "Back" is pressed. few caveats though:

  1. It assumes you added all transactions to the backstack (using FragmentTransaction.addToBackStack())

  2. It will be activated upon each stack change (you can store other stuff in the back stack such as animation) so you might get multiple calls for the same instance of fragment.

Original source of answer here

Community
  • 1
  • 1
Mca Dc
  • 11
  • 6