Basic ViewPager usage with fragments

suggest change

A ViewPager allows to show multiple fragments in an activity that can be navigated by either fliping left or right. A ViewPager needs to be feed of either Views or Fragments by using a PagerAdapter.

There are however two more specific implementations that you will find most useful in case of using Fragments which are FragmentPagerAdapter and FragmentStatePagerAdapter. When a Fragment needs to be instantiated for the first time, getItem(position) will be called for each position that needs instantiating. The getCount() method will return the total number of pages so the ViewPager knows how many Fragments need to be shown.

Both FragmentPagerAdapter and FragmentStatePagerAdapter keep a cache of the Fragments that the ViewPager will need to show. By default the ViewPager will try to store a maximum of 3 Fragments that correspond to the currently visible Fragment, and the ones next to the right and left. Also FragmentStatePagerAdapter will keep the state of each of your fragments.

Be aware that both implementations assume your fragments will keep their positions, so if you keep a list of the fragments instead of having a static number of them as you can see in the getItem() method, you will need to create a subclass of PagerAdapter and override at least instantiateItem(),destroyItem() and getItemPosition()methods.

Just add a ViewPager in your layout as described in the basic example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout> 
    <android.support.v4.view.ViewPager
        android:id="@+id/vpPager"> 
    </android.support.v4.view.ViewPager>
</LinearLayout>

Then define the adapter that will determine how many pages exist and which fragment to display for each page of the adapter.

public class MyViewPagerActivity extends AppCompatActivity {
    private static final String TAG = MyViewPagerActivity.class.getName();

    private MyPagerAdapter mFragmentAdapter;
    private ViewPager mViewPager;

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

        //Apply the Adapter
        mFragmentAdapter = new MyPagerAdapter(getSupportFragmentManager());    
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        mViewPager.setAdapter(mFragmentAdapter);
    }

    private class MyPagerAdapter extends FragmentPagerAdapter{

        public MyPagerAdapter(FragmentManager supportFragmentManager) {
            super(supportFragmentManager);
        }

        // Returns the fragment to display for that page
        @Override
        public Fragment getItem(int position) {
            switch(position) {
                case 0:
                    return new Fragment1();

                case 1:
                    return new Fragment2();

                case 2:
                    return new Fragment3();

                default:
                    return null;
            }
        }

        // Returns total number of pages    
        @Override
        public int getCount() {
            return 3;
        }

    }
}

If you are using android.app.Fragment you have to add this dependency:

compile 'com.android.support:support-v13:25.3.1'

If you are using android.support.v4.app.Fragment you have to add this dependency:

compile 'com.android.support:support-fragment:25.3.1'

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


ViewPager:
* Basic ViewPager usage with fragments

Table Of Contents
2 Gradle
5 Intent
17 Service
19 WebView
28 ViewPager
31 SQLite
35 Glide
37 Dialog
38 ACRA
44 Handler
53 Toast
63 Menu
65 Picasso
70 Volley
71 Widgets
78 Realm
90 Spinner
95 OkHttp
108 TextView
109 ListView
111 Loader
118 Xposed
119 Security
121 ImageView
123 Doze Mode
130 Drawables
131 Colors
134 Fresco
139 AdMob
145 Keyboard
146 Button
150 EditText
155 Vk SDK
163 ExoPlayer
169 XMPP
175 OpenCV
177 Threads
184 ORMLite
186 TabLayout
190 LruCache
192 Zip files
194 Fastlane
199 FileIO
202 Moshi
210 VideoView
216 Paint
218 ProGuard
226 CleverTap
228 ADB shell
229 Ping ICMP
230 AIDL
234 Context
240 JCodec
242 Okio
249 FuseView
254 Looper
261 Fastjson
263 Jackson
267 Smartcard