Getting the current Fragment instance in the viewpager

前端 未结 30 1886
醉话见心
醉话见心 2020-11-22 08:56

Below is my code which has 3 Fragment classes each embedded with each of the 3 tabs on ViewPager. I have a menu option. As shown in the onOpt

30条回答
  •  粉色の甜心
    2020-11-22 09:18

    There are a lot of answers here that don't really address the basic fact that there's really NO WAY to do this predictably, and in a way that doesn't result you shooting yourself in the foot at some point in the future.

    FragmentStatePagerAdapter is the only class that knows how to reliably access the fragments that are tracked by the FragmentManager - any attempt to try and guess the fragment's id or tag is not reliable, long-term. And attempts to track the instances manually will likely not work well when state is saved/restored, because FragmentStatePagerAdapter may well not call the callbacks when it restores the state.

    About the only thing that I've been able to make work is copying the code for FragmentStatePagerAdapter and adding a method that returns the fragment, given a position (mFragments.get(pos)). Note that this method assumes that the fragment is actually available (i.e. it was visible at some point).

    If you're particularly adventurous, you can use reflection to access the elements of the private mFragments list, but then we're back to square one (the name of the list is not guaranteed to stay the same).

提交回复
热议问题