New to android and recently learned swipe views a bit. In my app, it has 17 chapters and in each chapter, there will be 30 pages containing some text data, a user can swipe through. I need to use FragmentStatePagerAdapter to save memory but I need to know that do I need to make 510 Fragment objects, means 510 XML layout? I just need to change the text in each page, and I've seen many using switch statement like this
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentOne();
case 1:
return new FragmentTwo();
default:
break;
}
return null;
}
Do I/Should I write 30 cases in each chapter? or is there a better way to do this? I've Googled and seen lots of Youtube videos but couldn't find the solution. I request everyone that if you're answering or commenting, do explain your codes cause I believe in learning, not in copy pasting.
It's easy peasy man!
You need only one Fragment object, here's the code
public class FragmentChild extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
// INFLATE THE LAYOUT THAT EACH FRAGMENT OBJECT WILL HAVE, PUT IT IN A VIEW
View root = inflater.inflate(R.layout.couplets, container, false);
// RECEIVE THE BUNDLE DATA SENT (ARGUMENTS)
Bundle args = getArguments();
// CREATE AN ARRAY LIST OF STRINGS THAT WILL HOLD TEXT
ArrayList<String> someText = new ArrayList<>();
someText.add("one");
someText.add("two");
someText.add("three");
TextView txt = (TextView) root.findViewById(R.id.text_view);
txt.setText(someText.get(args.getInt("position")));
return root;
}
custom pager adapter
class MyFragmentAdapter extends FragmentStatePagerAdapter {
MyFragmentAdapter(FragmentManager fm) {super(fm);}
@Override
public Fragment getItem(int position) {
Bundle args = new Bundle();
args.putInt("position", position);
Fragment fragment = new FragmentChild();
fragment.setArguments(args);
return fragment;
}
@Override
public int getCount() {
return 3;
}
}
And finally host activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chapter_one);
// FIND THE VIEWPAGER AND SET THE CUSTOM ADAPTER TO IT TO PROVIDE CHILD PAGES
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
MyFragmentAdapter adapter = new MyFragmentAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
}
}