Android SlideShow using ViewPager and Page Indicator Example

In this tutorial, we are going to learn how to create Android SlideShow using ViewPager and Page Indicator. There are situations in your android app development that might require you to develop a slide show. A typical example is image gallery app or news headline app.

Android provides different options on how to create a slideshow but in this tutorial, we will focus on using android ViewPager.

If you are interested in using android ViewFlipper I will suggest you read my tutorial on Android Slideshow using ViewFlipper.

Android ViewPager is a layout manager that let you flip from left to right through pages of data. It uses a PageAdapter to bind ViewPager interface. There are few different ways in which it can be constructed. The most common approach is using a Fragment. Each Fragment represents a page.

If you are new to ViewPager I will suggest you read my tutorial on Understanding ViewPager and PageAdapter.

This tutorial will follow part of what has been discussed in the above mentioned tutorial. In this tutorial. we are going to create our Activity class with its corresponding layout file.

The layout file will contain a Viewpager widget and also some Radio Button widgets. The Radio Button widgets will use as a Page Indication which let users to have a feel of the number of the currently displayed image.

So, we will create a subclass of the PageAdapter and a layout file which the PageAdapter will inflate. The layout file will contain all the widgets we want in the ViewPager interface.

In other to get a visual understanding of what we are going to create in this android tutorial, I have add below some screen shots from the application.

 

SOME SCREENSHOT FROM THE APPLICATION

android viewpager slideshow

 

CREATE NEW ANDROID PROJECT

Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 24

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidViewpagerSlide

Package: com.inducesmile.androidviewpagerslide

Select Empty Activity

Name your activity: MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

 

hot_deal_layout.xml

Now we will create a new layout file in our project layout folder inside the res folder. Right click on the layout folder, select new > XML > Layout XML file. In the open dialog, name the layout file hot_deal_layout.xml or anything you like. Open the layout file and add the code below to it.

<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/direction_card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="1dp"
    card_view:cardElevation="@dimen/_3sdp"
    card_view:cardUseCompatPadding="true">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="@dimen/_16sdp"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:paddingBottom="@dimen/_8sdp"
            android:paddingLeft="@dimen/_16sdp"
            android:paddingRight="@dimen/_16sdp"
            android:paddingTop="@dimen/_8sdp">
            <ImageView
                android:id="@+id/hot_deal_favorite"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:adjustViewBounds="false"
                android:contentDescription="@string/app_name"
                android:src="@drawable/favorite_icon" />
            <TextView
                android:id="@+id/hot_deal_price"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="5"
                android:gravity="end"
                android:text="@string/price"
                android:textColor="@color/colorAccent"
                android:textSize="@dimen/_14sdp"
                android:textStyle="bold" />
        </LinearLayout>
        <ImageView
            android:id="@+id/hot_deal_food_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="@dimen/_12sdp"
            android:adjustViewBounds="true"
            android:contentDescription="@string/app_name"
            android:scaleType="centerCrop"
            android:src="@drawable/dish" />
        <TextView
            android:id="@+id/hot_deal_food_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="@dimen/_12sdp"
            android:text="@string/salad_cream"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/_14sdp"
            android:textStyle="bold" />
        <TextView
            android:id="@+id/hot_deal_food_description"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="@dimen/_8sdp"
            android:paddingLeft="@dimen/_16sdp"
            android:paddingRight="@dimen/_16sdp"
            android:text="@string/test"
            android:textColor="@color/colorBlack"
            android:textSize="@dimen/_12sdp" />
    </LinearLayout>
</android.support.v7.widget.CardView>

 

CustomViewPagerAdapter.java

We will create a subclass of the PagerAdapter. Right click on your project package folder and select New > Java class and name the java class CustomViewPagerAdapter.java or a name of your choice.

Open that PagerAdapter class you just created and add the code below to the class.

import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.inducesmile.androidfoodordering.R;
import com.inducesmile.androidfoodordering.entities.HotDealObject;
import java.util.List;
public class CustomViewPagerAdapter extends PagerAdapter{
    private Context context;
    private List<HotDealObject> hotDealList;
    private LayoutInflater layoutInflater;
    public CustomViewPagerAdapter(Context context, List<HotDealObject> hotDealList) {
        this.context = context;
        this.hotDealList = hotDealList;
        this.layoutInflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
    }
    @Override
    public int getCount() {
        return hotDealList.size();
    }
    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == ((View)object);
    }
    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
    }
    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View view = layoutInflater.inflate(R.layout.hot_deal_layout, container, false);
        HotDealObject mHotDealObject = hotDealList.get(position);
        ImageView favoriteIcon = (ImageView)view.findViewById(R.id.hot_deal_favorite);
        TextView hotDealPrice = (TextView)view.findViewById(R.id.hot_deal_price);
        ImageView hotDealFoodImage = (ImageView)view.findViewById(R.id.hot_deal_food_image);
        TextView hotDealFoodName = (TextView)view.findViewById(R.id.hot_deal_food_name);
        TextView hotDealFoodDescription = (TextView)view.findViewById(R.id.hot_deal_food_description);
        //bind value to the View Widgets
        hotDealPrice.setText(mHotDealObject.getDealPrice());
        hotDealFoodName.setText(mHotDealObject.getDealName());
        hotDealFoodDescription.setText(mHotDealObject.getDealDescription());
        container.addView(view);
        return view;
    }
}

We will create a new Activity page with its corresponding layout file. Follow the same process we have used before but in this case we will select empty activity. Name your activity class HotDealActivity.java and the layout file activity_hot_deals_activity.xml.

 

activity_hot_deals_activity.xml

In this layout file, we are going to add a Viewpager widget and some group radio buttons as explained before. Open the layout file and add the copy and paste the code below inside the file.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_hot_deal_actvity"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.inducesmile.androidfoodordering.HotDealActvity">
    <android.support.v4.view.ViewPager
        android:id="@+id/hot_deal_view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="@dimen/_8sdp"
        android:layout_gravity="top"
        android:layout_marginBottom="@dimen/_40sdp"
        android:scrollbars="none">
    </android.support.v4.view.ViewPager>
        <RadioGroup
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal|bottom"
            android:orientation="horizontal"
            android:id="@+id/radiogroup">
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/radioButton"
                android:checked="true" />
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/radioButton2" />
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/radioButton3" />
        </RadioGroup>
</FrameLayout>

 

HotDealActivity.java

In HotDealsActivity class, we will get the instances of the view widgets in the layout file. Thereafter, instantiate the CustomViewPagerAdapter.java class and pass it as a parameter to Viewpager setAdapter() method.

We will instantiate a Handle object which we will use to post delay and update the UI view once the current item position in the adapter is changed.

Use the setOnPageChangeListener() method to determine the current position of adapter and in turn set the corresponding radio button that matches the position.

Open the HotDealActivity.java class and add the code below.

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioGroup;
import com.inducesmile.androidfoodordering.adapter.CustomViewPagerAdapter;
import com.inducesmile.androidfoodordering.adapter.SlideshowPagerAdapter;
import com.inducesmile.androidfoodordering.entities.HotDealObject;
import java.util.ArrayList;
import java.util.List;
public class HotDealActvity extends AppCompatActivity {
    private static final String TAG = HotDealActvity.class.getSimpleName();
    private ViewPager viewPager;
    private CustomViewPagerAdapter mAdapter;
    private Handler handler;
    private final int delay = 2000;
    private int page = 0;
    Runnable runnable = new Runnable() {
        public void run() {
            if (mAdapter.getCount() == page) {
                page = 0;
            } else {
                page++;
            }
            viewPager.setCurrentItem(page, true);
            handler.postDelayed(this, delay);
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hot_deal_actvity);
        setTitle(getString(R.string.hot_deal_menus));
        final RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radiogroup);
        handler = new Handler();
        viewPager = (ViewPager)findViewById(R.id.hot_deal_view_pager);
        mAdapter = new CustomViewPagerAdapter(HotDealActvity.this, getTestData());
        SlideshowPagerAdapter adapter = new SlideshowPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(mAdapter);
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                page = position;
                switch (position){
                    case 0:
                        radioGroup.check(R.id.radioButton);
                        break;
                    case 1:
                        radioGroup.check(R.id.radioButton2);
                        break;
                    case 2:
                        radioGroup.check(R.id.radioButton3);
                        break;
                }
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }
    public List<HotDealObject> getTestData() {
        List<HotDealObject> mTestData = new ArrayList<HotDealObject>();
        mTestData.add(new HotDealObject("$42.00", "", "Fried Fish with Sauce", "It is a long established fact that a reader will be distracted by the when looking at its layout.It is a long established fact that a reader will be distracted by the when looking at its layout"));
        mTestData.add(new HotDealObject("$30.00", "", "Rice and Bean with Sauce", "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC It is a long established fact that a reader will be distracted by the when looking at its layout"));
        mTestData.add(new HotDealObject("$23.00", "", "Baked Potato with Salad", "There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour It is a long established fact that a reader will be distracted by the when looking at its layout"));
        return mTestData;
    }
    @Override
    protected void onResume() {
        super.onResume();
        handler.postDelayed(runnable, delay);
    }
    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacks(runnable);
    }
}

This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email address to be among the first to receive my new android blog post once it is published.

6 Comments

    • Inducesmile

Add a Comment