Use one Fragment in a ViewPager multiple times

android, android-viewpager, dynamic, fragment

Solution

You can instantiate the same Fragment class for every page in your ViewPager, passing the position of the ViewPager to control what to display. Something like that:

public class MyFragment extends Fragment {

    private int mIndex;

    public MyFragment(int index) {
        mIndex = index;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {

        switch(mIndex){
            case 0:
            // do you things..
            case 1:
            // etcetera
        }             
    }
}

then, in you FragmentPagerAdapter:

public static class MyAdapter extends FragmentPagerAdapter {
    public MyAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return NUM_ITEMS;
    }

    @Override
    public Fragment getItem(int position) {
        return new MyFragment(position);
    }
}

That way you can reuse most of your code changing only what you need in the switch/case statement.

Problem

Is it possible to use one fragment in a viewpager multiple times? I am trying to build a dynamically updated UI using ViewPager. I want to use the same design, basically the same fragment with different data for every page, like a listview adapter.

Original source