Use one fragment at a time in ViewPager

Is it possible to use one fragment in viewpager several times? I am trying to create a dynamically updated interface using ViewPager. I want to use the same design, basically the same fragment with different data for each page, for example using the listview adapter.

+6
source share
2 answers

You can create the same fragment class for each page of your ViewPager by passing the ViewPager position to control the 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 you have the 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); } } 

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

+4
source

You misunderstood the concept of class compared to object of class . Your source code, MyFragment.java defines the class that you turn into a living creature every time you create it using the new ( new MyFragment(); ) operator - this creates an object , which is an instance your class . If you do not intentionally prevent this (for example, using the Singleton template), you can do as many instances class as you want, just as you are allowed to do as many cakes as one recipe uses. And this also applies to fragments.

So, while you create a separate object (aka said instance ) of your class for each page, you will have to do what you want.

+3
source

All Articles