Thursday, June 6, 2013

ViewPaper and Fragment: How to update data of active fragment item

For example, I use ViewPaper to flip left and right through pages of data. But when a fragment item has been active, I need to update some related data and state.

So, I need to implement the fragment adapter that extends from FragmentStatePagerAdapter and override methods to keep reference from position to fragment item, in this case, we can use HashMap but in Android SDK recommend, I used SparseArray to keep this reference. On the activity or fragment parent, implement listener OnPageChangeListener for PageIndicator to detect the position of fragment item has been activated and update related data's state.

The adapter can implement as following:

public static class MyAdapter extends FragmentStatePagerAdapter {
    private SparseArray<TestFragment> mPageReferenceMap 
                              = new SparseArray<TestFragment>();
    ...

    @Override 
    public Object instantiateItem(ViewGroup viewGroup, int position) {
        Object obj = super.instantiateItem(viewGroup, position);

        //Add the reference when fragment has been create or restore
        if (obj instanceof TestFragment) {
                TestFragment f= (TestFragment)obj;
                mPageReferenceMap.put(position, f);
        }

        return obj;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        //Remove the reference when destroy it
        mPageReferenceMap.remove(position);

        super.destroyItem(container, position, object);
    }

    public TestFragment getFragment(int key) {

        return mPageReferenceMap.get(key);
    }
    ...
}

Hope this help.