Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p><strong>* EDIT *</strong></p> <p>As @ElliotM pointed out, there is a better solution. No need to change anything in your adapter, just get the fragment with:</p> <pre><code>Fragment myFragment = (Fragment) adapter.instantiateItem(viewPager, viewPager.getCurrentItem()); </code></pre> <p><strong>* OLD SOLUTION *</strong></p> <p>Best option is the second solution here: <a href="http://tamsler.blogspot.nl/2011/11/android-viewpager-and-fragments-part-ii.html" rel="noreferrer">http://tamsler.blogspot.nl/2011/11/android-viewpager-and-fragments-part-ii.html</a></p> <p>In short: you keep track of all the "active" fragment pages. In this case, you keep track of the fragment pages in the FragmentStatePagerAdapter, which is used by the ViewPager..</p> <pre><code>public Fragment getItem(int index) { Fragment myFragment = MyFragment.newInstance(); mPageReferenceMap.put(index, myFragment); return myFragment; } </code></pre> <p>To avoid keeping a reference to "inactive" fragment pages, we need to implement the FragmentStatePagerAdapter's destroyItem(...) method:</p> <pre><code>public void destroyItem(View container, int position, Object object) { super.destroyItem(container, position, object); mPageReferenceMap.remove(position); } </code></pre> <p>... and when you need to access the currently visible page, you then call:</p> <pre><code>int index = mViewPager.getCurrentItem(); MyAdapter adapter = ((MyAdapter)mViewPager.getAdapter()); MyFragment fragment = adapter.getFragment(index); </code></pre> <p>... where the MyAdapter's getFragment(int) method looks like this:</p> <pre><code>public MyFragment getFragment(int key) { return mPageReferenceMap.get(key); } </code></pre> <p>--- EDIT:</p> <p>Also add this in your adapter, for after an orientation change:</p> <pre><code>/** * After an orientation change, the fragments are saved in the adapter, and * I don't want to double save them: I will retrieve them and put them in my * list again here. */ @Override public Object instantiateItem(ViewGroup container, int position) { MyFragment fragment = (MyFragment) super.instantiateItem(container, position); mPageReferenceMap.put(position, fragment); return fragment; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload