Update data in ListFragment as part of ViewPager

后端 未结 10 1858
一整个雨季
一整个雨季 2020-11-22 07:55

I\'m using the v4 compatibility ViewPager in Android. My FragmentActivity has a bunch of data which is to be displayed in different ways on different pages in my ViewPager.

10条回答
  •  情歌与酒
    2020-11-22 08:41

    Barkside's answer works with FragmentPagerAdapter but doesn't work with FragmentStatePagerAdapter, because it doesn't set tags on fragments it passes to FragmentManager.

    With FragmentStatePagerAdapter it seems we can get by, using its instantiateItem(ViewGroup container, int position) call. It returns reference to fragment at position position. If FragmentStatePagerAdapter already holds reference to fragment in question, instantiateItem just returns reference to that fragment, and doesn't call getItem() to instantiate it again.

    So, suppose, I'm currently looking at fragment #50, and want to access fragment #49. Since they are close, there's a good chance the #49 will be already instantiated. So,

    ViewPager pager = findViewById(R.id.viewpager);
    FragmentStatePagerAdapter a = (FragmentStatePagerAdapter) pager.getAdapter();
    MyFragment f49 = (MyFragment) a.instantiateItem(pager, 49)
    

提交回复
热议问题