neX
neX

Reputation: 35

Replace Fragment in ViewPager

I am following example from Android doc example here: https://developer.android.com/training/animation/screen-slide.html

I was wondering if I want several different fragments on each page then what would be the best approach.

This is my MainActivity, as you can see I open new fragment class for each page position:

public class MainActivity extends AppCompatActivity {

    /**
     * The number of pages (wizard steps) to show in this demo.
     */
    private static final int NUM_PAGES = 4;

    /**
     * The pager widget, which handles animation and allows swiping horizontally to access previous
     * and next wizard steps.
     */
    private ViewPager mPager;

    /**
     * The pager adapter, which provides the pages to the view pager widget.
     */
    private PagerAdapter mPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new MainActivity.ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
    }

    @Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() == 0) {
            // If the user is currently looking at the first step, allow the system to handle the
            // Back button. This calls finish() on this activity and pops the back stack.
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }

    /**
     * A simple pager adapter that represents 4 HeartsPageFragment objects, in
     * sequence.
     */
    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:
                    return new HeartsPageFragment();
                case 1:
                    return new DiamondsPageFragment();
                case 2:
                    return new ClubsPageFragment();
                case 3:
                    return new SpadesPageFragment();
            }
            return null;
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }
}

This is one of the fragment classes, all four are almost same:

public class ClubsPageFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(
                R.layout.view_clubs, container, false);

        return rootView;
    }

}

I was wondering if it's best approach to have four different fragment classes for each page? I feel like this is repetition and bad, but I am not sure how I could fix this. It is lagging on my phone to when I switch between those. Any tips would be welcome.

Edit:

Here is the code for the layout.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/content_suit"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/first_row_hearts">

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView1"
            android:layout_marginEnd="10dp"
            android:src="@drawable/spades_2"/>

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView2"
            android:layout_marginEnd="10dp"
            android:src="@drawable/spades_3"/>

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView3"
            android:layout_marginEnd="10dp"
            android:src="@drawable/spades_4"/>

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView4"
            android:src="@drawable/spades_5"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/second_row_hearts"
        android:layout_below="@id/first_row_hearts"
        android:layout_marginTop="10dp">

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView5"
            android:layout_marginEnd="10dp"
            android:src="@drawable/spades_6" />

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView6"
            android:layout_marginEnd="10dp"
            android:src="@drawable/spades_7" />

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView7"
            android:layout_marginEnd="10dp"
            android:src="@drawable/spades_8" />

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView8"
            android:src="@drawable/spades_9" />


    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/third_row_hearts"
        android:layout_below="@id/second_row_hearts"
        android:layout_marginTop="10dp">

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView9"
            android:layout_marginEnd="10dp"
            android:src="@drawable/spades_10" />

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView10"
            android:layout_marginEnd="10dp"
            android:src="@drawable/spades_jack" />

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView11"
            android:layout_marginEnd="10dp"
            android:src="@drawable/spades_queen" />

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView12"
            android:layout_marginEnd="10dp"
            android:src="@drawable/spades_king"/>
    </LinearLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/fourth_row_hearts"
        android:layout_below="@+id/third_row_hearts"
        android:layout_marginTop="10dp">

        <ImageView
            android:layout_width="80dp"
            android:layout_height="112dp"
            android:id="@+id/imageView13"
            android:layout_marginEnd="10dp"
            android:src="@drawable/spades_ace"/>
    </LinearLayout>


</RelativeLayout>

Upvotes: 0

Views: 78

Answers (1)

ice spirit
ice spirit

Reputation: 1535

If you donot want to make different fragment classes study this auto generated code of tabbed activity android.

public class MainActivity extends AppCompatActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link FragmentPagerAdapter} derivative, which will keep every
 * loaded fragment in memory. If this becomes too memory intensive, it
 * may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
private SectionsPagerAdapter mSectionsPagerAdapter;

/**
 * The {@link ViewPager} that will host the section contents.
 */
private ViewPager mViewPager;

LeftDrawerLayout mLeftDrawerLayout;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.container);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(mViewPager);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public PlaceholderFragment() {
    }
    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }
}
/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        // getItem is called to instantiate the fragment for the given page.
        // Return a PlaceholderFragment (defined as a static inner class below).
        return PlaceholderFragment.newInstance(position + 1);
    }

    @Override
    public int getCount() {
        // Show 7 total pages.
        return 7;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return "SECTION 1";
            case 1:
                return "SECTION 2";
            case 2:
                return "SECTION 3";
            case 3:
                return "SECTION 4";
            case 4:
                return "SECTION 5";
            case 5:
                return "SECTION 6";
            case 6:
                return "SECTION 7";
        }
        return null;
    }
}

}

Upvotes: 2

Related Questions