-2

We have to know the current fragment which is the visible mode in pager adapter, but unable to process.

for (Fragment fragment : getChildFragmentManager().getFragments()) {
    if (fragment instanceof OffLineSyncedFragment && fragment.isVisible() && fragment.isVisible()) {
        ((OffLineSyncedFragment) fragment).confirmDeleteAlert(getActivity(), documentHelper, false, isDocument, null);
    }
    else if(fragment instanceof OffLineFailedFragment && fragment.isVisible()){

    }
}

This is my code which is not working.

Jonas
  • 6,915
  • 8
  • 35
  • 53
  • give your fragments a tag and use that tag to identify the fragment – Ezio May 18 '17 at 05:55
  • There are several ways to do this based on the purpose. If you can say why exactly you want to query the active fragment, I can provide the relevant solution. – Mohammed Atif May 18 '17 at 05:58

2 Answers2

0

ViewPager.OnPageChangeListener is the correct approach here. And as you have noticed, onPageSelected(int position) doesn't get called until the page is centered. So when the page is properly centered it will give you the fragment that is currently visible.,

Anmol317
  • 1,356
  • 1
  • 14
  • 31
0

There is some ways to do it. first easy and straight you can set page change listener on your view pager :

  viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(final int i, final float v, final int i2) {
    }
    @Override
    public void onPageSelected(final int i) {
        // If you are user FragmentPagerAdapter below is the right way to get fragment
        Fragment fragment= getChildFragmentManager().findFragmentByTag("android:switcher:" + R.id.viewPager_card_exchanger + ":" + i);

        if(fragment!=null){
            // Do your stuff here 
        }
    }
    @Override
    public void onPageScrollStateChanged(final int i) {
    }
});

Or You can override the the fragment method as below:

 @Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        System.out.println("VISIBLE");
    } else {
        System.out.println("GONE");
    }
}
ADM
  • 20,406
  • 11
  • 52
  • 83