Search code examples
androidandroid-fragmentsandroid-viewpager

Unable to get visible/live Fragment


I am stuck in this problem.

I want to maintain live instance of Fragment in application context. What I did is

1st Attempt

public class BaseProjectFragmentParent extends BaseProjectFragment {
    @Override
    public void onResume() {
        super.onResume();
        App.getInstance().setLiveFragment(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        App.getInstance().setLiveFragment(null);
    }
}

and I extend all fragments by this base class. I expected live instance to be there in Application class.

Problem is in ViewPager, I have two Fragment in ViewPager where both Fragment's onResume() is called and live instance is set the second Fragment. I am working on some common code so I don't want to use getCurrentItem().

Second Attempt

Next I tried to get this Live Fragment by getSupportFragmentManager().getFragments()

  1. isVisible() is true for both Fragments. (Not useful)
  2. isResumed() is true for both Fragments. (Not useful)

Solution

  • You can use

    setUserVisibleHint(boolean isVisibleToUser)
    

    In fragments. This flag is set by the OS when a fragment becomes visible:

    class MyFragment extends Fragment {
    
        public MyFragment() {
            setUserVisibleHint(false) //This is needed because by default its true 
        }
    
        @Override
        public void setUserVisibleHint(boolean isVisibleToUser) {
             super.setUserVisibleHint(isVisibleToUser)
             //true if fragment is visible
        }
    }
    

    However this wont get called inside Viewpager. You have to add a listener to the viewpager and then set your active page manually:

    viewPager.addOnPageChangeListener(new OnPageChangeListener() {
    public void onPageScrollStateChanged(int state) {}
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
    
    public void onPageSelected(int position) {
        // Check if this is the page you want.
    }
    });