Android ViewPager with multiple fragment classes each w / separate layout file

My application uses the android.support.v4.view.ViewPager class. For each page in the ViewPager, I want there to be one fragment, each with its own layout file. Each fragment is defined in its own file. It’s hard for me to implement this. To clarify, there are:

1 ViewPager
4 Fragment files - FragmentOne.class, FragmentTwo.class, FragmentThree.class, FragmentFour.class
4 XML layout files - frag_one.xml, frag_two.xml, frag_three.xml, frag_four.xml

The examples I saw relate to only one layout file.

Here is my FragmentActivity where the ViewPager is located:

 public class Main extends FragmentActivity { MyAdapter mAdapter; ViewPager mPager; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mAdapter = new MyAdapter(getSupportFragmentManager()); mPager = (ViewPager) findViewById(R.id.pager); mPager.setAdapter(mAdapter); } public static class MyAdapter extends FragmentPagerAdapter { public MyAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return 4; } @Override public Fragment getItem(int position) { return EditorFragment.newInstance(position); } } } 

My main question is: how do I get the MyAdapter adapter to recognize four separate fragment files and smoothly list them through ViewPager? What changes should I make to getItem() ?

Any help is appreciated.

EDIT:

So, I tried what lulumeya suggested, and came up with this:

EDIT 2: Yes, these interruption statements documented this. He is working now. Thanks to everyone who helped! Now I have a good segregation, thanks.

  @Override public Fragment getItem(int position) { Fragment f = new Fragment(); switch (position) { case 0: f = FragmentOne.newInstance(position); break; case 1: f = FragmentTwo.newInstance(position); break; case 2: f = FragmentThree.newInstance(position); break; case 3: f = FragmentFour.newInstance(position); break; } return f; } 

The lauches app, which is always a good sign, but stuck on the fourth layout. When I find the page on the right, it is also layout four, for all pages. I am sure that I changed the layout to inflation for each fragment. I will still work on it. @lulumeya - Is that what you had in mind?

+4
source share
1 answer

Just return the corresponding instance of the fragment to getItem (int position) by position. Using switch ~ case, easy.

+5
source

Source: https://habr.com/ru/post/1394821/


All Articles