Android ViewFlipper Example Tutorial

Filed Under: Android

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 example

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.


<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.journaldev.viewflipper.MainActivity"
    tools:showIn="@layout/activity_main">

    <ViewFlipper
        android:id="@+id/view_flipper"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_gravity="center"
                android:adjustViewBounds="true"
                android:background="@android:color/black"
                android:scaleType="centerCrop" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:text="First Child"
                android:textColor="@android:color/white"
                android:textSize="18dp"
                android:textStyle="bold" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_gravity="center"
                android:adjustViewBounds="true"
                android:background="@android:color/darker_gray"
                android:scaleType="centerCrop" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:text="Second Child"
                android:textSize="18dp"
                android:textStyle="bold" />
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent">

            <ImageView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_gravity="center"
                android:adjustViewBounds="true"
                android:background="@android:color/holo_green_light"
                android:scaleType="centerCrop" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:gravity="center"
                android:text="Third Child"
                android:textSize="18dp"
                android:textStyle="bold" />
        </RelativeLayout>
    </ViewFlipper>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_alignParentTop="true"
        android:gravity="center"
        android:orientation="horizontal">

        <Button
            android:id="@+id/play"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginRight="10dp"
            android:background="@android:drawable/ic_media_play" />

        <Button
            android:id="@+id/stop"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@android:drawable/ic_media_pause" />
    </LinearLayout>


</RelativeLayout>

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


<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate
        android:fromXDelta="-100%" android:toXDelta="0%"
        android:fromYDelta="0%" android:toYDelta="0%"
        android:duration="1400" />
</set>

in_from_right.xml


<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate
        android:fromXDelta="100%" android:toXDelta="0%"
        android:fromYDelta="0%" android:toYDelta="0%"
        android:duration="1400" />
</set>

out_from_left.xml


<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate android:fromXDelta="0%" android:toXDelta="-100%"
        android:fromYDelta="0%" android:toYDelta="0%"
        android:duration="1400"/>
</set>

out_from_right.xml


<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <translate android:fromXDelta="0%" android:toXDelta="100%"
        android:fromYDelta="0%" android:toYDelta="0%"
        android:duration="1400"/>
</set>

The MainActivity.java is defined as below.


public class MainActivity extends AppCompatActivity {

    private ViewFlipper mViewFlipper;
    private Context mContext;
    private float initialX;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mContext = this;
        mViewFlipper = (ViewFlipper) this.findViewById(R.id.view_flipper);

        findViewById(R.id.play).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewFlipper.setAutoStart(true);
                mViewFlipper.setFlipInterval(1000);
                mViewFlipper.startFlipping();
                Snackbar.make(view, "Automatic view flipping has started", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });


        findViewById(R.id.stop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mViewFlipper.stopFlipping();

                Snackbar.make(view, "Automatic view flipping has stopped", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

    }

    @Override
    public boolean onTouchEvent(MotionEvent touchevent) {
        switch (touchevent.getAction()) {
            case MotionEvent.ACTION_DOWN:
                initialX = touchevent.getX();
                break;
            case MotionEvent.ACTION_UP:
                float finalX = touchevent.getX();
                if (initialX > finalX) {
                    if (mViewFlipper.getDisplayedChild() == 1)
                        break;

                    mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.in_from_left));
                    mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.out_from_left));

                    mViewFlipper.showNext();
                } else {
                    if (mViewFlipper.getDisplayedChild() == 0)
                        break;

                    mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.in_from_right));
                    mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.out_from_right));

                    mViewFlipper.showPrevious();
                }
                break;
        }
        return false;
    }
}

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.

Comments

  1. jacksam says:

    package com.login;

    import java.io.Serializable;

    /**
    * Created by Jai on 6/10/2017.
    */

    public class Pojo implements Serializable {
    String name;
    String loc;
    String usernam;
    String pass;

    public String getName() {
    return name;
    }

    public void setName(String name) {
    this.name = name;
    }

    public String getLoc() {
    return loc;
    }

    public void setLoc(String loc) {
    this.loc = loc;
    }

    public String getUsernam() {
    return usernam;
    }

    public void setUsernam(String usernam) {
    this.usernam = usernam;
    }

    public String getPass() {
    return pass;
    }

    public void setPass(String pass) {
    this.pass = pass;
    }
    }

  2. jacksam says:

    package com.login;

    import android.app.Activity;
    import android.content.Context;
    import android.os.Bundle;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;
    import android.widget.TextView;

    import java.util.ArrayList;

    public class list extends Activity {

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

    sqlite sqliteObj= new sqlite(list.this);
    ArrayList arrColle = sqliteObj.getall();

    ListView liView = (ListView)findViewById(R.id.lisv);
    CustonmAdapter cusObj = new CustonmAdapter(list.this,R.layout.adpater_view,arrColle);
    liView.setAdapter(cusObj);
    }

    public class CustonmAdapter extends ArrayAdapter
    {
    Context _con;
    int _layout;
    ArrayList arrObj;
    public CustonmAdapter(Context con , int layout, ArrayList arr)
    {
    super(con,layout,arr);
    _con = con;
    _layout = layout;
    arrObj = arr;
    }

    @Override
    public View getView(int position,View convertView,
    ViewGroup parent) {

    View v =null;
    LayoutInflater layou =(LayoutInflater)(list.this).getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    v = layou.inflate(_layout,null);
    Pojo poObj =arrObj.get(position);
    TextView tx = (TextView) v.findViewById(R.id.uName);
    TextView tx1 = (TextView)v.findViewById(R.id.pName);
    tx.setText(poObj.getUsernam());
    tx1.setText(poObj.getPass());
    return v;
    }
    }
    }

  3. jacksam says:

    package com.login;

    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.widget.Toast;

    import java.util.ArrayList;

    /**
    * Created by Jai on 6/10/2017.
    */

    public class sqlite extends SQLiteOpenHelper {
    private static final int Database_version = 1;
    private static final String Dbname = “log.db”;
    SQLiteDatabase db;

    Context con;
    public sqlite(Context context) {
    super(context, Dbname, null, 1);
    con = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    db.execSQL(“create table login (id integer primary key autoincrement,name varchar, unam varchar,loc varchar, pass varchar)”);

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL(“drop table if exists” + db);

    }

    public long insertAction(ContentValues cValuea, String tablename) {
    SQLiteDatabase db = this.getWritableDatabase();
    long i = db.insert(tablename, null, cValuea);
    db.close();
    return i;
    }

    public boolean login(String usr, String pass) {

    SQLiteDatabase dblogin = this.getReadableDatabase();
    Cursor cursor = dblogin.rawQuery(“select * from login where unam=? and pass=?”, new String[]{usr, pass});
    if (cursor.getCount() > 0) {
    return true;
    }
    return false;
    }

    public ArrayList getall() {
    SQLiteDatabase dball = this.getWritableDatabase();
    Cursor all = dball.rawQuery(“select * from login”,null);
    ArrayList li = new ArrayList();
    while(all.moveToNext())
    {
    Pojo p =new Pojo();
    p.setUsernam(all.getString(2));
    p.setPass(all.getString(4));
    li.add(p);
    }

    return li;

    }

    }

  4. jacksam says:

    package com.login;

    import android.app.Activity;
    import android.content.ContentValues;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    import static android.R.attr.name;

    public class SignActivity extends Activity {

    TextView snam,pass,loc,con,uname;
    EditText enam,epass,email,econ,eunam;
    Button subtn;
    sqlite sq;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sign);

    enam = (EditText) findViewById(R.id.sena);
    epass = (EditText) findViewById(R.id.sepas);
    email = (EditText) findViewById(R.id.semail);
    econ = (EditText) findViewById(R.id.secpas);
    eunam = (EditText) findViewById(R.id.seuna);
    subtn = (Button) findViewById(R.id.subtn);

    subtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

    if (enam.getText().toString().equals(“”)|| email.getText().toString().equals(“”)) {

    enam.setError(“field is empty”);
    }
    else {

    ContentValues conValue = new ContentValues();
    conValue.put(“name”, enam.getText().toString());
    conValue.put(“loc”, email.getText().toString());
    conValue.put(“unam”, eunam.getText().toString());
    conValue.put(“pass”, epass.getText().toString());
    sqlite sqli = new sqlite(SignActivity.this);
    long i = sqli.insertAction(conValue, “login”);
    Toast.makeText(SignActivity.this, “successfully entered”+i, Toast.LENGTH_LONG).show();

    enam.setText(“”);
    email.setText(“”);
    epass.setText(“”);
    econ.setText(“”);
    eunam.setText(“”);
    }
    }
    });
    }
    }

  5. jacksam says:

    package com.login;

    import android.app.Activity;
    import android.app.AlertDialog;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    public class MainActivity extends Activity {
    String username,password;
    EditText user,pas;
    TextView unam,pass;
    Button lbt,sbt,fpas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    user = (EditText)findViewById(R.id.urn);
    pas=(EditText)findViewById(R.id.pass);
    unam = (TextView)findViewById(R.id.ur);
    pass = (TextView)findViewById(R.id.pa);
    lbt = (Button)findViewById(R.id.lbt);
    sbt =(Button)findViewById(R.id.sbtn);
    fpas=(Button)findViewById(R.id.fpas);

    sbt.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Intent si = new Intent(MainActivity.this,SignActivity.class);
    startActivity(si);
    }
    });

    lbt.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    username = user.getText().toString();
    password = pas.getText().toString();

    sqlite sq = new sqlite(MainActivity.this);
    boolean b = sq.login(username,password);

    if (b==true) {
    Intent it = new Intent(MainActivity.this,list .class);
    Toast.makeText(MainActivity.this,”welcome ” +username,Toast.LENGTH_LONG).show();

    startActivity(it);

    }
    else {
    Toast.makeText(MainActivity.this,”wrong username/password”,Toast.LENGTH_LONG).show();
    }
    }
    });

    fpas.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Intent fp = new Intent(MainActivity.this,Forgot.class);
    startActivity(fp);
    }
    });

    }
    }

  6. droid says:

    how to make the same fliper without play and pause.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages