Android: Simple ViewPager with Views

You can quickly and easily use a ViewPager with views--instead of fragments--by first setting its XML:


And then setting its adapter.

ViewPager mViewPager = (ViewPager) findViewById(;
mViewPager.setAdapter(new PagerAdapter() {
    String[] titles = {"Eins", "Zwei", "Drei"};
    int[] layouts = {R.layout.layout1, R.layout.layout2, R.layout.layout3};

    public Object instantiateItem(ViewGroup container, int position) {
        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        ViewGroup layout = (ViewGroup) inflater.inflate(layouts[position], container, false);
        return layout;

    public void destroyItem(ViewGroup container, int position, Object object) {

    public CharSequence getPageTitle(int position) {
        return titles[position];

    public int getCount() {
        return layouts.length;

    public boolean isViewFromObject(View view, Object object) {
        return view == object;

Note, we're setting the layouts as IDs, and initialising them in the initantiateItem method.

We include titles, but they won't show on their own. We'll use them with a TabLayout next.

android android-viewpager

Edit on github
comments powered by Disqus
Click me