Use one Fragment in a ViewPager multiple times

2020-07-10 19:36发布

问题:

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.

回答1:

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.



回答2:

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.