Tutorials  /  JavaScript

Swipe Through Pages: A Handy Tutorial on Android ViewPager

Ccentron Redaktion · October 2024 ·4 min read ·JavaScript, Tutorial

Discover everything about implementing Android ViewPagers in our latest blog post! Dive into an interactive tutorial that guides you step by step on setting up a ViewPager and creating custom screens with examples.

What is Android ViewPager?

The Android ViewPager widget, located in the Support Library, allows users to swipe left or right to see a completely new screen. Today, we'll implement a ViewPager using views and PagerAdapters. While we could also implement the same with fragments, we'll discuss that in a later tutorial. The ViewPager uses a PagerAdapter, whose task is to provide views for the MainActivity, similar to how a ListAdapter does for a ListView.

Example Code for Android ViewPager

The activity_main.xml consists solely of the ViewPager, as shown below:

Code
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>

</RelativeLayout>

MainActivity.java

The MainActivity.java looks like this:

Go
package com.journaldev.viewpager;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

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));
    }

}

The role of MainActivity in the above code is simply to reference the ViewPager and set the CustomPagerAdapter, which extends the PagerAdapter. Before discussing the CustomPagerAdapter class, let's look at the ModelObject class.

The ModelObject Class

The enum above lists all pages of the ViewPagers. There are three pages with their respective layouts. The layout of a single page is as follows:

Code
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="@android:color/holo_blue_dark"
android:layout_height="match_parent">

<!-- TextViews go here -->

</RelativeLayout>

The remaining two pages have similar layouts and are included in this project's source code.

The CustomPagerAdapter Class

Go
package com.journaldev.viewpager;

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class CustomPagerAdapter extends PagerAdapter {

// Methods go here

}

1. CustomPagerAdapter(Context context): The constructor requires a Context reference. The context is stored as a class variable since it will be used later to access individual page templates from the enum class.

2. instantiateItem: In this case, we use the enum and inflate the specific layout associated with the enum value. Then we add the newly inflated layout to the ViewGroup (collection of views) maintained by the PagerAdapter, and then return this layout. The object returned by this method is also later used as the second parameter in the isViewFromObject method.

3. destroyItem: This method removes a particular view from the ViewGroup maintained by the PagerAdapter.

4. getCount: It simply returns the number of views maintained by the ViewPager. In this example, it's the number of enum values in the model object.

5. isViewFromObject: This method checks whether a specific object belongs to a particular position, which is straightforward. As mentioned earlier, the second parameter is of type Object and corresponds to the return value from the instantiateItem method.

6. getPageTitle: At a particular position, we need to provide a title to the PagerAdapter. This usually manifests in the ActionBar as the title of the activity, or sometimes tabs hook into this method to label each tab. In this case, we've kept it just for labeling.

The image below shows the app in action. That concludes the tutorial on Android ViewPager. You can download the Android ViewPager project via the link below.

VM

Matching infrastructure at centron

Node applications need somewhere to run: ccloud³ VMs with full root access from €3.12 per month – or as a managed server if you would rather not run it yourself. Rent a cloud server →

Conclusion

Android ViewPager is a powerful tool for creating screens that can be swiped horizontally. With the right setup and use of PagerAdapters, developers can create engaging and interactive user interfaces.

That's it for today! We hope this tutorial has helped you better understand Android ViewPager and how to use it in your own projects. Until next time!

Jetzt 200 € Guthaben sichern

Testen Sie Ihr Setup auf ccloud³

Registrieren Sie sich in der ccloud³ und erhalten Sie 200 € Startguthaben für Ihr Projekt – z. B. für eine PostgreSQL-VM mit automatischen Backups.

centron Redaktion Technische Redaktion

Das Redaktionsteam von centron schreibt Anleitungen aus dem Betriebsalltag: getestet auf unserer eigenen Plattform, betrieben im Rechenzentrum in Hallstadt bei Bamberg.

Kategorie JavaScript
Teilen
Noch offene Fragen?

Our team will help you with your specific setup - in German or English, by people who run the platform themselves.

War dieses Tutorial hilfreich?

Your answer is stored anonymously and helps us improve our tutorials.

Kommentare

No comments yet - be the first to ask a question about this tutorial.

Sign in to comment

Comments are open to centron customers. Sign in to your account to ask a question about this tutorial.

Weiterlesen

Das könnte Sie auch interessieren

Jetzt kostenlos anfangen

Melden Sie sich an und erhalten Sie in den ersten 60 Tagen ein Guthaben von 200 € bei centron.

Dieses Werbeangebot gilt nur für neue Konten. Angebot ausschließlich für Gewerbetreibende.

Jetzt loslegen Sales kontaktieren