Search

ViewPager Without Fragments

Matt Compton

4 min read

Jul 30, 2015

ViewPager Without Fragments

Every once in a while, an Android developer might want to use a ViewPager without the added complexity of also using Fragments. A good example is an image gallery, where the user can swipe between different pictures. On these types of pages, all you really want to display is a view of static content (in this case, an image), so I’m going to walk you through how to utilize the ViewPager with just plain-old Views and layouts.

Initial Setup

Your journey begins with laying some foundational work with an XML layout, a build.gradle file and the Activity that the ViewPager will live in.

layout/activity_main.xml

Here’s your XML layout for the Activity, which consists solely of a ViewPager.

<android.support.v4.view.ViewPager
    android:id="@+id/viewpager"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    />

build.gradle

Don’t forget to add the support library as a gradle dependency. In newer versions of Android Studio, this should be added automatically at project creation.

dependencies {
    compile 'com.android.support:support-v4:22.0.0'
}

MainActivity.java

Next you setup an Activity:

public class MainActivity extends AppCompatActivity {

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

        ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setAdapter(new CustomPagerAdapter(this));
    }

}

Nothing too exciting here, just grabbing a reference to your ViewPager and then setting its adapter to the super-special CustomPagerAdapter that will be covered later. This initial setup could also be done in a Fragment’s onCreateView() method.

Need to know how to keep your development project on track and in budget? Download your eBook.

Model Object

Personally, I like to have a model object representing the possible pages in the ViewPager. The below enum is essentially a listing of all of your ViewPager’s pages, with tidbits of information about each one thrown in, such as the page title and the layout to be shown. In reality, this could contain any information specific to a particular screen in your ViewPager.

public enum CustomPagerEnum {

    RED(R.string.red, R.layout.view_red),
    BLUE(R.string.blue, R.layout.view_blue),
    ORANGE(R.string.orange, R.layout.view_orange);

    private int mTitleResId;
    private int mLayoutResId;

    CustomPagerEnum(int titleResId, int layoutResId) {
        mTitleResId = titleResId;
        mLayoutResId = layoutResId;
    }

    public int getTitleResId() {
        return mTitleResId;
    }

    public int getLayoutResId() {
        return mLayoutResId;
    }

}

Again, this enum isn’t strictly necessary, but it helps organize the separation of the content (the actual screen being shown) and the controller (the ViewPager).

PagerAdaper

The PagerAdapter is the core piece of this exercise. Everything that you’ve done so far is to make your life a bit easier when dealing with the PagerAdapter. So, here it is:

public class CustomPagerAdapter extends PagerAdapter {

    private Context mContext;

    public CustomPagerAdapter(Context context) {
        mContext = context;
    }

    @Override
    public Object instantiateItem(ViewGroup collection, int position) {
        CustomPagerEnum customPagerEnum = CustomPagerEnum.values()[position];
        LayoutInflater inflater = LayoutInflater.from(mContext);
        ViewGroup layout = (ViewGroup) inflater.inflate(customPagerEnum.getLayoutResId(), collection, false);
        collection.addView(layout);
        return layout;
    }

    @Override
    public void destroyItem(ViewGroup collection, int position, Object view) {
        collection.removeView((View) view);
    }

    @Override
    public int getCount() {
        return CustomPagerEnum.values().length;
    }

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

    @Override
    public CharSequence getPageTitle(int position) {
        CustomPagerEnum customPagerEnum = CustomPagerEnum.values()[position];
        return mContext.getString(customPagerEnum.getTitleResId());
    }

}

There’s a lot going on here, but don’t fret. Step by step, here’s each piece of the puzzle:

  • CustomPagerAdapter(Context context): The constructor needs a Context reference, since you’ll want to access some string and layout resources later on. You just save the Context as a member variable of the class.
  • instantiateItem: Using the LayoutInflater, you can inflate any desired XML layout. In this case, you use the enum and inflate the particular enum value’s associated layout. Next, you add the newly inflated layout to the collection of Views maintained by the PagerAdapter, and then you return that layout. The object being returned by this method is also used later on, as the second parameter in the isViewFromObject method. Both refer to a particular item in the PagerAdapter. In this case, it’s a View.
  • destroyItem: This method removes a particular view from the collection of Views maintained by the PagerAdapter.
  • getCount: You simply return the number of views that will be maintained by the ViewPager. For this example, the count is the number of enum values in the model object.
  • isViewFromObject: This method checks whether a particular object belongs to a given position, which is made simple in this example—just check whether the View equals the object (i.e., points to the same reference). As noted earlier, the second parameter is of type Object and is the same as the return value from the instantiateItem method.
  • getPageTitle: At a given position, you need to supply the PagerAdapter with a title. This usually manifests itself in the ActionBar as the Activity’s title, or sometimes tabs will hook into this method for labelling each tab.

While the PagerAdapter consists of many small pieces, each piece serves a unique and simple purpose.

Bon Voyage!

So now, if you need a ViewPager full of static content but don’t want the heavy-handedness of Fragments, you have a nifty guide to using a ViewPager and PagerAdapter dedicated to displaying solely Views. Enjoy life without Fragments!

Mark Dalrymple

Reviewer Big Nerd Ranch

MarkD is a long-time Unix and Mac developer, having worked at AOL, Google, and several start-ups over the years.  He’s the author of Advanced Mac OS X Programming: The Big Nerd Ranch Guide, over 100 blog posts for Big Nerd Ranch, and an occasional speaker at conferences. Believing in the power of community, he’s a co-founder of CocoaHeads, an international Mac and iPhone meetup, and runs the Pittsburgh PA chapter. In his spare time, he plays orchestral and swing band music.

Speak with a Nerd

Schedule a call today! Our team of Nerds are ready to help

Let's Talk

Related Posts

We are ready to discuss your needs.

Not applicable? Click here to schedule a call.

Stay in Touch WITH Big Nerd Ranch News