Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use one Fragment in a ViewPager multiple times

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.

like image 994
József Vesza Avatar asked Nov 17 '12 15:11

József Vesza


2 Answers

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.

like image 155
Frankie Avatar answered Oct 04 '22 06:10

Frankie


You misunderstood the concept of class versus object of class. Your MyFragment.java source code defines class which you turn into "living thing" each time you instantiate it with new operator (new MyFragment();) - this creates object which is an instance of your class. Unless you intentionally prevent this (by i.e. using Singleton pattern) your can make as many instances of the class as you like, same way you are allowed to make as many i.e. cakes using single recipe. And this applies to fragments as well.

So as long as you create separate object (aka said instance) of your class for each page, you should be able to do what you want.

like image 33
Marcin Orlowski Avatar answered Oct 04 '22 06:10

Marcin Orlowski