0

I have a main Activity which XML holds a RelativeLayout with a ViewPager:

<android.support.v4.view.ViewPager
    android:id="@+id/pager"

Then I have a FragmentStatePagerAdapter to manage the Fragment.

Now I have a public method on the Fragment called getFoo() (which obviously returns foo).

Question: What is the correct way to get the Fragment's foo from the main Activity?

I tried using addOnPageChangeListener() on the ViewPager, but then I'm not able to get the active instance of the Fragment.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
0leg
  • 13,464
  • 16
  • 70
  • 94
  • "Tried to use addOnPageChangeListener on the ViewPager, but then - unable to get active instance of the Fragment" - If you have passed list of fragments to your viewpager adapter, you can retrieve Fragment on index in onPageChanged() – Krupal Shah Dec 10 '16 at 08:10

1 Answers1

2

You can extend FragmentStatePagerAdapter much like having your own ArrayAdapter.

Hold a List<Fragment> in that (passed through the constructor), then just use adapter.getItem(position).getFoo()

Very minimal example.

public MyFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
    private List<Fragment> fragments;

    public MyFragmentStatePagerAdapter(FragmentManager fm, List<Fragment> fragments) {
        super(fm);
        this.fragments = fragments;
    }

    public int getCount() { return fragments.size(); }
    public Fragment getItem(int position) { return fragments.get(position); }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • This is the correct approach, I think. I was using this tutorial: https://developer.android.com/training/animation/screen-slide.html where things defined a bit different, but your approach is the one I am moving away with now. – 0leg Dec 12 '16 at 08:13
  • That guide recreates a fragment everytime you slide to it. This answer provides the ability to "save the state" of all the Fragments – OneCricketeer Dec 12 '16 at 08:15
  • Yes. I want the app to create list of seven slides (for the days of the week). So user can slide between them. If user goes "outside" week range - the slides will be destroyed and another 7 slides created. The data for each group will be saved/fetched from the database. – 0leg Dec 12 '16 at 08:18
  • There are better ways to handle making a continuing ViewPager than destroying and adding more. – OneCricketeer Dec 12 '16 at 13:18
  • Can you tell please, in a few words - what is the better way? I will search for more info on it myself then. – 0leg Dec 13 '16 at 07:22
  • 1
    Something like an infinite viewpager. Add the 7 fragments once, you can keep scrolling. http://stackoverflow.com/questions/13668588/infinite-scrolling-image-viewpager – OneCricketeer Dec 13 '16 at 15:27