In this tutorial we’ll discuss and implement Android ViewFlipper. ViewFlipper in android is mainly used in cases when we need to transform one view into another.

Android ViewFlipper

ViewFlipper in android is an extension of ViewAnimator class, which animates between two or more views that have been added to it. Only one child is shown at a time and the user can flip to view the other child views. We can also implement the ViewFlipper such that it automatically flips between the views at regular intervals. A ViewFlipper can be used in gallery apps to navigate between the images.

Android ViewFlipper supports the methods : setInAnimation() and setOutAnimation() in which we can use either the default animation from the android system or the write our own animation class. To control the auto-flip option, we can start and stop the timer on the ViewFlipper by invoking startFlipping() and stopFlipping() methods. We can set the auto flip interval using setFlipInterval(period). The next and previous child views are invoked using showNext() and showPrevious() methods on the ViewFlipper object.

In this tutorial we’ll create an application that consists of 3 screens. We’ll show automatic flipping on each of them and use Android MotionEvent class to swipe left and right to flip between the first two screens.

Android ViewFlipper Example Project Structure

android-viewflipper-project

This project consists of four custom animation classes that will show transitions between the ViewFlipper views.

Android ViewFlipper Example Code

The content_main.xml file is defined as shown below.

The ViewFlipper tag consists of three sibling RelativeLayout child views. Only one will be displayed at a time.

The four animation classes are placed in res/anim folder and are defined as below :
in_from_left.xml

in_from_right.xml

out_from_left.xml

out_from_right.xml

The MainActivity.java is defined as below.

The onTouchEvent method is implemented to detect swipes.

MotionEvent.ACTION_DOWN is the action when the touch gesture has first started and it notes the location.

MotionEvent.ACTION_UP marks the touch gesture as finished and also gives the intermediate points since the last action.

If we’re on the first child and a gesture from left to right is made the ViewFlipper would animate and display the second child. Vice-versa for the opposite gesture.

Pressing the play button, animates and flips between the child views automatically at regular intervals.

The application output in action is shown below.

viewflipper in android, android viewflipper app

This brings an end to Android ViewFlipper tutorial. You can download the final Android ViewFlipper Project from the link below.

By admin

Leave a Reply