Android: Viewpager and FragmentStatePageAdapter
Asked Answered
M

5

9

I'm designing an app that allows users to flip between multiple pages in a ViewPager. I've been struggling trying to figure out how it is possible to remove a Fragment instance from a page when it is no longer visible on screen, cache it (to, say, a HashMap), and then restore it so that when the user flips back to that page, the views and everything else in it will be in the same state it was before removal. For example, my first page is a login screen that makes certain layout elements on that particular page visible/invisible on a successful login. When I flip forward enough pages then flip back to the first page, the layout is reset. This becomes more of a problem for another one of my pages which contains a huge, horizontal/vertical scrolling grid of data that I use a thread in the background to draw when it initializes. I use a progress dialog to notify the user of loading progress and that becomes really annoying everytime I have to load it.

So I did some research...

I browsed through the source code for FragmentStatePageAdapter and in the destroyItem() callback, the state of the Fragment instance being removed is saved to an ArrayList. When a new instance of the Fragment is being created in the instantiateItem() callback, if an instance of an item doesn't already exist (they keep track of this by using an ArrayList), a new Fragment instance is created and its saved state is initialized with the corresponding Fragment.SavedState data. Unfortunately, this data does not include the state that the Views were in although I noticed that for pages with a GridView/ListView, the state of the Views were somehow restored (if I scrolled to some random position, flipped a few pages and came back, it would not be reset).

According to the API:

The saved state can not contain dependencies on other fragments -- that is it can't use putFragment(Bundle, String, Fragment) to store a fragment reference because that reference may not be valid when this saved state is later used. Likewise the Fragment's target and result code are not included in this state.

Being a noob to Android, I'm not quite sure I understand the last statement.

That being said, is there any way to cache View state? If not, I think I'll just go ahead and go with leaving all the fragment pages in memory.

Mush answered 2/8, 2011 at 6:19 Comment(0)
W
4

I had the same problem problem and solved it by implementing these two functions

    public void onSaveInstanceState (Bundle outState)
    public void onActivityCreated (Bundle savedInstanceState)

on the fragments that I wanted to save. On the first function, you should save in the Bundle the date that you need to restore the views ( in my case I had a bunch of spinner so I used an int array to save their positions). The second function, which is called when restoring your fragment, is where you implement the restoring process.

I hope this helps. I also made my adapter to inherit from FragmentStatePageAdapter but I am not sure that this is mandatory.

Walton answered 11/8, 2011 at 17:30 Comment(1)
You need to inherit from FragmentStatePagerAdapter, if you only use FragmentPagerAdapter then onSaveInstanceState will not be called.Margo
D
2

Listing of main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView android:text="Page 1" android:id="@+id/textViewHeader"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:gravity="center" android:padding="10dip" android:textStyle="bold"></TextView>
    <android.support.v4.view.ViewPager
        android:layout_width="fill_parent" android:layout_height="fill_parent"
        android:id="@+id/viewPager" />
</LinearLayout>

Setting up the ViewPager

ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager);
MyPagerAdapter adapter = new MyPagerAdapter(this);
viewPager.setAdapter(adapter);

The PagerAdapter

@Override
public void destroyItem(View view, int arg1, Object object) {
         ((ViewPager) view).removeView((View)object);
}
@Override
public int getCount() {
          return views.size();
}
@Override
public Object instantiateItem(View view, int position) {
           View view = views.get(position);
           ((ViewPager) view).addView(view);
           return view;
}
@Override
public boolean isViewFromObject(View view, Object object) {
           return view == object;
}

look here for more details view pager example

Decumbent answered 2/11, 2011 at 16:3 Comment(0)
P
1

Looking at the various documentation pieces, my best guess is that the views you are creating do not have an ID attached to them. Assuming that the fragment's saved state is created from Fragment.onSaveInstanceState, then the fragment will automatically save any view's state that has an id. You probably have a default id associated with your ListView/GridView if you created them from a layout file. You can also associate an id with the views by calling setId.

Also, for your custom filled fragment, you may also have to do something custom in onSaveInstanceState.

Pulsometer answered 5/8, 2011 at 13:48 Comment(0)
A
0

Here's an example of how I implemented caching in PagerAdapter. After filling the cache all future view requests are served from cache, only data is replaced.

public class TestPageAdapter extends PagerAdapter{

private int MAX_SIZE = 3;
private ArrayList<SoftReference<View>> pageCache = new ArrayList<SoftReference<View>>(3);


public TestPageAdapter(Context context){
    // do some initialization
}

@Override
public int getCount() {
    // number of pages
}

private void addToCache(View view){
    if (pageCache.size() < MAX_SIZE){
        pageCache.add(new SoftReference<View>(view));
    } else {
        for(int n = (pageCache.size()-1); n >= 0; n--) {
            SoftReference<View> cachedView = pageCache.get(n);
            if (cachedView.get() == null){
                pageCache.set(n, new SoftReference<View>(view));
                return;
            }
        }
    }
}

private View fetchFromCache(){
    for(int n = (pageCache.size()-1);  n>= 0; n--) {
        SoftReference<View> reference = pageCache.remove(n);
        View view = reference.get();
        if (view != null) {
            return view;
        }
    }
    return null;
}

@Override
public Object instantiateItem(View collection, int position) {
    View view = fetchFromCache();
    if (view == null) {
        // not in cache, inflate manually
        LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        view = inflater.inflate(R.layout.page, null);
    } 
    setData(view, position);
    ((ViewPager) collection).addView(view, 0);
    return view;         
}

private void setData(View view, int position){
    // set page data (images, text ....)
}

public void setPrimaryItem(ViewGroup container, int position, Object object) {
    currentItem = (View)object;
}

public View getCurrentItem() {
    return currentItem;
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((View) object);
}

@Override
public void destroyItem(View collection, int arg1, Object view) {
    ((ViewPager) collection).removeView((View) view);
    addToCache((View) view);
}

}
Ansermet answered 3/10, 2012 at 8:58 Comment(0)
A
0

I also ran into this problem when I was using PagerSlidingTabStrip and using and instance of FragmentPagerAdapter, switching to FragmentStatePagerAdapter definitely worked.

Then I use onSaveInstanceState() to save sate

Amsden answered 10/4, 2015 at 14:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.