nephilimrising nephilimrising - 10 months ago 54
Android Question

Android viewpager fragment

I need to create an app with one activity and 3 fragments in it. Pages don't need to be dynamically created but its a plus. My question is: do I need a separate fragment for every view or I can reuse one with different view?I've read the android tutorial here
for view pager and it left me with that impression. Its an important project. I am a noob so pls explain for such.

Answer Source

I'm assuming you want 3 full screen fragments. Use a ViewPager with a FragmentPagerAdapter.

public class MyFragment extends Fragment {

    ViewPager viewPager;
    MyPagerAdapter pagerAdapter;

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.my_fragment, container, false);

    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        pagerAdapter = new MyPagerAdapter(getFragmentManager());



    android:layout_height="match_parent" />

public class MyPagerAdapter extends FragmentPagerAdapter {

    static final int NUM_PAGES = 3;

    public MyPagerAdapter(FragmentManager fm) {

    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return new Fragment1();
            case 1:
                return new Fragment2();
            case 2:
                return new Fragment3();

    public int getCount() {
        return NUM_PAGES;

This will allow swiping right or left to switch between the fragments. You will have to use a TabLayout, bottom navigation, buttons, or some other way to switch between them besides swiping. I'll leave that for you to figure out ;)