Create Android Image Slideshow using Android ViewFlipper

In this tutorial, we are going to learn how to create android image Slideshow using android ViewFlipper.

If you have not heard of android ViewFlipper or you have not used it before, then in order to understand what Android ViewFlipper is and when to use it, the paragraph below explains it.

Android ViewFlipper is a subclass of a ViewAnimator class. It is use to animate between two or more views that have been added to it. The important aspect of android ViewFlipper is that only one of its child view is shown at a particular time.

It has a built-in auto-start flip which can automatically flip between each child at a regular interval.

To work with android ViewFlipper, it is important to know the following public methods associated with ViewFlipper.

1. getAccessibilityClassName() – Return the class name of this object to be used for accessibility purposes.

2. isAutoStart() – Returns true if this view automatically calls startFlipping() when it becomes attached to a window.

3. isFlipping() – Returns true if the child views are flipping.

4. setAutoStart(boolean autoStart) – Set if this view automatically calls startFlipping() when it becomes attached to a window.

5. setFlipInterval(int milliseconds) – How long to wait before flipping to the next view

6. startFlipping() – Start a timer to cycle through child views.

7. stopFlipping() – No more flips

In this android example, we are going to use ImageView widgets as children to the ViewFlipper. We will get the instance of the ViewFlipper and call the startFlipping() on it.

Since we are going to combine auto-start flipping and manual flipping through button click event, we will initialize a boolean flag that will switch us between the two states

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 viewflipper androidslideshowone

 

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: AndroidViewFlippers

Package: com.inducesmile.androidviewflippers

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.

 

Build.Gradle

We are going to use a third party library in this tutorial. Although it is not compulsory and you can do with it. Open the file and add the code below.

apply plugin: 'com.android.application'
apply plugin: 'com.android.application'
android {
    compileSdkVersion 25
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.inducesmile.androidviewflippers"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.0.0'
    compile 'com.intuit.sdp:sdp-android:1.0.3'
    testCompile 'junit:junit:4.12'
}

 

STRINGS.XML

We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

<resources>
    <string name="app_name">Android ViewFlipper</string>
    <string name="slideshow_on">Slideshow On</string>
</resources>

 

COLORS.XML

Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#cc55c7</color>
    <color name="colorPrimaryDark">#B21AAC</color>
    <color name="colorAccent">#4cffe8</color>
    <color name="colorPrimaryLight">#ffd532</color>
    <color name="colorBlack">#000000</color>
</resources>

 

Slideshow Image Resources

Since we make use of different images in the ViewFlipper, I have added the image resources in the drawable folder of this project. Feel free to change the images to your choice images.

 

activity_main.xml

Now is time to create the main layout file of our ViewFlipper android application. We are going to add some button, ImageView and ViewFlipper widgets in the layout file.

The layout file is simple and easy to understand. Open the activity_main.xml and add the code below to it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/colorPrimaryLight"
    tools:context="com.inducesmile.androidviewflippers.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimaryDark"
        android:paddingBottom="@dimen/_8sdp"
        android:paddingTop="@dimen/_8sdp"
        android:orientation="vertical">
        <Button
            android:id="@+id/slideshow_toggle_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/app_name"
            android:padding="@dimen/_16sdp"
            android:background="@color/colorPrimaryLight"
            android:textColor="@color/colorBlack"
            android:text="@string/slideshow_on"
            android:layout_gravity="center"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:gravity="center"
            android:orientation="vertical">
            <ImageView
                android:id="@+id/left_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:contentDescription="@string/app_name"
                android:src="@drawable/leftarrow" />
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="6"
            android:gravity="center"
            android:orientation="vertical">
            <ViewFlipper
                android:id="@+id/image_view_flipper"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
                <ImageView
                    android:id="@+id/image_one"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:adjustViewBounds="true"
                    android:contentDescription="@string/app_name"
                    android:src="@drawable/orange" />
                <ImageView
                    android:id="@+id/image_two"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:adjustViewBounds="true"
                    android:contentDescription="@string/app_name"
                    android:src="@drawable/apple" />
                <ImageView
                    android:id="@+id/image_three"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:adjustViewBounds="true"
                    android:contentDescription="@string/app_name"
                    android:src="@drawable/banana" />
                <ImageView
                    android:id="@+id/image_four"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:adjustViewBounds="true"
                    android:contentDescription="@string/app_name"
                    android:src="@drawable/berry" />
            </ViewFlipper>
        </LinearLayout>
        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="2"
            android:gravity="center"
            android:orientation="vertical">
            <ImageView
                android:id="@+id/right_button"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:contentDescription="@string/app_name"
                android:src="@drawable/rightarrow" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

 

MainActivity.java class

In the MainActivity class, we are going to get the instances of all the View widgets in the layout file we created above.

We will use the two ImageView widgets for left and right arrow controls. So when theisSlideshowOn = false; then the app will switch to left and right arrow. When it is true, the auto flipping will start automatically.

For smooth flipping of images, we will create a fade-in and fade-out animation that will be attached to the instance of the android ViewFlipper.

Open the MainActivity class and add the code below to the class.

import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ViewFlipper;
public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int FLIP_DURATION = 3000;
    private ViewFlipper viewFlipper;
    private boolean isSlideshowOn = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        ActionBar actionBar = getSupportActionBar();
        if(null != actionBar){
            actionBar.hide();
        }
        viewFlipper = (ViewFlipper)findViewById(R.id.image_view_flipper);
        viewFlipper.setInAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_in));
        viewFlipper.setOutAnimation(AnimationUtils.loadAnimation(this, R.anim.fade_out));
        ImageView leftArrowButton = (ImageView)findViewById(R.id.left_button);
        leftArrowButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isSlideshowOn) {
                    viewFlipper.showPrevious();
                }
            }
        });
        ImageView rightArrowButton = (ImageView)findViewById(R.id.right_button);
        rightArrowButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!isSlideshowOn) {
                    viewFlipper.showNext();
                }
            }
        });
        Button slideshowToggleButton = (Button)findViewById(R.id.slideshow_toggle_button);
        slideshowToggleButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isSlideshowOn){
                    isSlideshowOn = false;
                }else{
                    isSlideshowOn = true;
                }
                if(isSlideshowOn){
                    startSlideshow();
                    animateSlideshow();
                }else{
                    stopSlideshow();
                }
            }
        });
    }
    private void startSlideshow(){
        if(!viewFlipper.isFlipping()){
            viewFlipper.setAutoStart(true);
            viewFlipper.setFlipInterval(FLIP_DURATION);
            viewFlipper.startFlipping();
        }
    }
    private void animateSlideshow(){
        viewFlipper.getInAnimation().setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }
            @Override
            public void onAnimationEnd(Animation animation) {
            }
            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }
    private void stopSlideshow(){
        if(viewFlipper.isFlipping()){
            viewFlipper.stopFlipping();
        }
    }
}

 

Anim Folder

Since will use a fade-in and fade-out animation for ViewFlipper child transition, we are going to create two different XML animation resource files.

These animation resource layouts will be created inside the anim folder in the res folder. If the folder is not yet create then create it first and add the follow animation layout files in it.

fade_in.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <alpha
        android:fromAlpha="0.1"
        android:toAlpha="1.0"
        android:duration="2000" />
</set>

 

fade_out.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <alpha
        android:fromAlpha="1.0"
        android:toAlpha="0.1"
        android:duration="2000"/>
</set>

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.

One Response

Add a Comment