Fragment onResume() isn't called when using FragmentPagerAdapter

后端 未结 2 2038
悲哀的现实
悲哀的现实 2021-02-10 00:23

I need my fragments to always call a certain function when they are the active fragment, so I put it in onResume(), but it isn\'t being called.

Fragment A



        
相关标签:
2条回答
  • 2021-02-10 01:12

    Override Fragment.setUserVisibleHint. When setUserVisibleHint is true call same logic you use for onResume.

    You can see when FragmentPagerAdapter calls setUserVisibleHint in instantiateItem and setPrimaryItem. Applicable to android since 4.2.1 and support-v4.

    0 讨论(0)
  • 2021-02-10 01:26

    I had the same problem while ago.

    Create a new interface and implement it by both of your Fragments:

    public interface OnPageSelectedListener {
        void onPageSelected();
    }
    

    In parent activity implement android.support.v4.view.ViewPager.OnPageChangeListener and call Fragment method like this:

    @Override
    public void onPageSelected(int i) {
        OnPageSelectedListener fragment = (OnPageSelectedListener ((PlaceListPagerAdapter)pager.getAdapter()).getFragment(i);
        fragment.onPageSelected();
    }
    

    PS: Name of the new interface and its method is a bit confusing, so be careful or change it.

    0 讨论(0)
提交回复
热议问题