Android: Switching screens in an Activity with animations (using ViewFlipper)

Posted May 26th @ 11:48 pm by Boyan Tsolov

Advertisement

In this post I’ll show you how to add animations when trying to switch between screens. Usually when you switch between screens it’s a direct “poof” and the new screen appears in a very un-graceful way. The SDK offers a bunch of easy-to-use animations, and I’ll show you how to use them here.

I tried doing animations on the opening and closing of activities, but I haven’t figured that out yet fully. So instead, I will show you how to use animations when switching on objects/layers inside the same activity. It will still look like you are switching screens, but all the layout data will be in one single XML. If we were to switch between activities, each activity would have had (usually) its own layout XML.

And in the post coming after this one, I’ll show you how to start this animation and switch the screen while dragging your fingers on the touch screen. Let me be a little more precise: while dragging one finger on the touch screen. I’m not sure if the OS handles multi-touch right now – or if that’s something the device has to enable – or both.

Back to the topic: how to switch between layers using animations to make it look like you are changing screens… we will be using a ViewFlipper widget in the layout XML.

1. Create a new Android project, unless you already have one

01 new project

2. Create a new Activity class that extends android.app.Activity.

02 new class

3. Create a new directory under the /res directory and call it anim

03 res directory

4. Right-click on the new directory called anim and Import all the XML files from: Android_SDK\Platform\android-1.5\samples\ApiDemos\res\anim.

These are animations created using XML. The same animations can be created in code, but these are ready for us to use in XML.

04 anim directory

5. Open res\layout\main.xml and copy/paste the following in:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    >

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

        <LinearLayout
               android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#ffffff">

            <TextView android:id="@+id/tv_country"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:textStyle="bold"
            android:textSize="18px"
            android:text="Country" >
            </TextView>
            <Spinner android:text=""
            android:id="@+id/spinner_country"
            android:layout_width="200px"
            android:layout_height="55px">
            </Spinner>
            <Button android:text="Next"
            android:id="@+id/Button_next"
            android:layout_width="250px"
                android:textSize="18px"
            android:layout_height="55px">
        </Button>
        </LinearLayout> 

        <LinearLayout
               android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#ffffff">

            <TextView android:id="@+id/tv_income"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#000000"
            android:textStyle="bold"
            android:textSize="18px"
            android:text="Income" >
            </TextView>
            <EditText android:text=""
            android:id="@+id/et_income"
            android:layout_width="200px"
            android:layout_height="55px">
            </EditText>
            <Button android:text="Previous"
            android:id="@+id/Button_previous"
            android:layout_width="250px"
                android:textSize="18px"
            android:layout_height="55px">
            </Button>
        </LinearLayout> 

    </ViewFlipper>        

</LinearLayout>

This is a little long, let’s inspect it more closely.

  • The outmost layer is a LinearLayout.
  • It contains only one inner layer: ViewFlipper
  • The first-level layers inside ViewFlipper will be the screens!
      • ViewFlipper contains 2 LinearLayouts. Each LinearLayout is 1 screen.
  • The first LinearLayout contains a label, a spinner (a dropdown), and a button
  • The second LinearLayout contains a label, an edit view (input box), and a button

6. Here is what Activity1.cs looks like:

package com.warriorpoint.taxman3;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.ViewFlipper;

public class Activity1 extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set main.XML as the layout for this Activity
        setContentView(R.layout.main);

        // Add a few countries to the spinner
        Spinner spinnerCountries = (Spinner) findViewById(R.id.spinner_country);
        ArrayAdapter countryArrayAdapter = new ArrayAdapter(this,
                    android.R.layout.simple_spinner_dropdown_item,
                    new String[] { "Canada", "USA" });
        spinnerCountries.setAdapter(countryArrayAdapter);

        // Set the listener for Button_Next, a quick and dirty way to create a listener
        Button buttonNext = (Button) findViewById(R.id.Button_next);
        buttonNext.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                // Get the ViewFlipper from the layout
                ViewFlipper vf = (ViewFlipper) findViewById(R.id.details);

                // Set an animation from res/anim: I pick push left in
                vf.setAnimation(AnimationUtils.loadAnimation(view.getContext(), R.anim.push_left_in));
                vf.showNext();
        }
        });

        // Set the listener for Button_Previous, a quick and dirty way to create a listener
        Button buttonPrevious = (Button) findViewById(R.id.Button_previous);
        buttonPrevious.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                // Get the ViewFlipper from the layout
                ViewFlipper vf = (ViewFlipper) findViewById(R.id.details);
                // Set an animation from res/anim: I pick push left out
                vf.setAnimation(AnimationUtils.loadAnimation(view.getContext(), R.anim.push_left_out));
                vf.showPrevious();
        }

        });        

    }
}

Let’s try and decipher the code:

  • First I set the main.xml to be the layout for this Activity
  • I input Canada and USA as the values in my dropdown (the Spinner object)
  • Then I create two listeners for the two buttons that I have Button_next and Button_previous
  • Each button does the following:
      • Gets a reference to the ViewFlipper
      • Sets an animation by passing it the context of this class and an animation from a res/anim XML file
      • showNext() or showPrevious() is called – which literally flips between the LinearLayouts in the ViewFlipper widget in the main.xml either forwards or backwards

That’s it! Run it!

Look at that fancy Spinner!

05 spinner

Click Next and watch it flow!

06 animation

Disclaimer: There is a problem with the back animation when you press “Previous”. It flickers a little and doesn’t flow properly backwards. I still have to figure out why. If anyone knows why, drop me a comment below!

Next up: Removing the “Next” and “Previous” buttons and switching screens by using your finger to drag on the touch screen.



4 Trackbacks/Pingbacks

  1. Pingback: Android: Switching screens by dragging over the touch screen | Warrior Point - Latest News on SaaS & Tutorials for On-demand Software on May 29, 2009
  2. Pingback: Android GUI examples on June 3, 2010
  3. Pingback: Animaciones para cambiar entre actividades | | AndroideityAndroideity on December 17, 2011
  4. Pingback: Sliding Image in imageView Android | Android Development tutorial | Android Development tutorial on September 28, 2012

38 Comments

  1. stephen
    June 6, 2009 at 04:16

    Hi for the disclaimer.. try using another animation R.anim.slide_right instead of push_left_out . thanks for the tutorial it’s really great!

  2. Boyan
    June 7, 2009 at 15:56

    Thanks Stephen, I’ll try it out!

  3. StarHan
    June 29, 2009 at 03:42

    why i can’t rotate an acitivity with y axle but it works well when a view rotates? Is there any difference between an acitivity and a view when they are appled rotateanimation which rotated with y axle?
    thanks for your help!

  4. jong10
    November 5, 2009 at 22:06

    Thank you! It’s great!!

  5. shining
    November 5, 2009 at 22:08

    WOW!!!! VERY NICE TIP!

    I have found this for a loooooooooooooong time!

    Thank you.

  6. tse
    January 26, 2010 at 01:57

    R.anim.push_left_in error

  7. tse
    January 26, 2010 at 01:57

    help me

  8. drne
    February 19, 2010 at 11:57

    In my case it just flicks, not animates, so it may be something with emulator. I have not tried it on the device.

  9. Tom
    March 3, 2010 at 15:44

    for the diclaimer, try to set 4 different animations

    next screen:
    vf.setInAnimation() … 100 -> 0 in the animation xml
    vf.setOutAnimation() … 0 -> -100 in the animation xml

    previous direction:
    vf.setInAnimation() … -100 -> 0 in the animation xml
    vf.setOutAnimation() … 0 -> 100 in the animation xml

  10. John
    April 6, 2010 at 04:54

    Hi all i am new to android .
    i want to develop calendar application in android.
    but i dont know how to start,if any one have examples related to android plz do mail me .

    Thanks and Regards
    john

  11. Somedude
    June 6, 2010 at 06:25

    In step 6 you wrote Activity1.cs instead of Activity1.java!!! Come on man :P Thanks anyhow for the great tutorial.. Keep it up!

  12. Matt
    July 8, 2010 at 15:22

    LOL, I can tell you’re an old C# developer; it’s not Activity1.cs, it’s Activity1.java :)

  13. rosebeat
    September 19, 2010 at 05:17

    Whenever I click on Next, I get the error “Application stopped unexpectedly” and I have to force close it. Why is that? Please help me. I have tried other examples of switching between the activites and the same thing happened. Whenever i click on next it gives me runtime error.
    Anyone has any idea why is it so?

  14. and
    September 23, 2010 at 06:17

    Have u kept the following code in AndroidManifest file

    hope this should work for you

  15. and
    September 23, 2010 at 06:17

    @rosebeat
    Have u kept the following code in AndroidManifest file

    hope this should work for you

  16. and
    September 23, 2010 at 06:21

    @rosebeat
    did u kept the foll code in AndroidManifest file

    hope this should work for you

  17. Baluk
    December 6, 2010 at 11:06

    Thanks for the helpful tutorial. I want to switch between activities by clicking a button through animate. This tutorials tells about multiple screens in one activity. So can any one tell me how to work with 2 with this animate file.

    Thank You,
    Baluk

  18. Sticker Printing Los Angeles CA
    December 23, 2010 at 02:47

    Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform using the Java programming language.

  19. Praveen
    December 24, 2010 at 03:46

    Hello John, I’m new to android and I also tried developing a simple calendar and I could do it. please tell me ur mail id I shall send u the sorce code, u can go thro it and understand.

    Hello Everybody,
    I need to change the layout view in my calendar application from month view to week view and day view as well. Here I should do it without changing the activity. Please someone help me in doing this with single activity.

    Thanks,
    Praveen.

  20. Shaiful
    February 8, 2011 at 04:15

    Can I get the source code for the animations?

  21. premsagar
    February 11, 2011 at 07:43

    how can i get animation of paper folding…?
    can i get source code for that?

  22. premsagar
    February 16, 2011 at 01:03

    Dear Sir,

    I’m new coming in Graphic development. And I need to compose a animation of Paper folding in Android.

    Anyone have tutorial or sample code for my reference?

  23. Appliance Repair Memphis TN
    February 25, 2011 at 02:42

    Android is a software stack for mobile devices that includes an operating system, middleware and key applications. The Android SDK provides the tools and APIs necessary to begin developing applications on the Android platform.

  24. beginner
    April 6, 2011 at 18:41

    Please provide a zipped file, that should make it less frustrating.

  25. Alex
    October 3, 2011 at 11:49

    This is the right blog for anyone who wants to find out about this topic. Great stuff, just great!

    Best regards Alex

  26. plo
    December 11, 2011 at 13:31

    my previous button is not working …force close is error

  27. Art
    March 3, 2012 at 14:09

    Can Anybody Help me????? Is it possible to drag between XML files????

  28. Luiz Verçosa
    March 22, 2012 at 17:52

    Very good! It helped me. Thanks!!!

  29. Brazilian dude
    May 23, 2012 at 18:19

    Thanks, dude… I was getting crazy with it. God bless you!

  30. Ashish
    June 5, 2012 at 07:10

    It really helps man, thanks allot for your contribution

  31. Davidson
    June 9, 2012 at 08:45

    I have got a lot problem getting my emulator to connect the connection breaks and it doe not display my project but it works fine I use windows xp please help me

  32. Olzhas
    June 26, 2012 at 01:53

    It’s possible to create animation between class or activities? If yes, how i can do it?

  33. Olzhas
    June 26, 2012 at 01:57

    It’s possible to create animation between class or activities? If yes, how i can do it?in class i use andengine, and i want switching class of andengine

  34. Sahar.b
    July 26, 2012 at 17:29

    I’m getting white screen before the slide animation..
    what should I do?

    Thnx!

  35. Andhika
    October 15, 2012 at 03:55

    Very good tutor, thanx !!
    I’am start create new project android now..

  36. Gezim
    March 6, 2013 at 04:24

    Hi guys, thanks for this post, I’m new here and I don’t know what is anim.push_left_in on this line vf.setAnimation(AnimationUtils.loadAnimation(view.getContext(), R.anim.push_left_in));
    In my R.java class I have no “anim” and I don’t know what should contains this anim, can anyone help me?

  37. gry komputerowe w biedronce
    April 13, 2014 at 05:38

    What i don’t understood is in truth how you are now not actually a lot more smartly-liked than you might be right now. You are so intelligent. You know thus considerably when it comes to this subject, made me in my opinion believe it from numerous varied angles. Its like women and men don’t seem to be involved until it’s something to accomplish with Girl gaga! Your own stuffs excellent. Always maintain it up!

  38. Laukendra
    July 31, 2015 at 09:17

    Hi, I am new in android. I have implemented an app in which
    I used the concept viewflipper; this is running successfully, but there is a problem according me. The problem is that, when I flip from one screen to another screen, there is white screen appearing between that screens. And, I want to see continuously screens in flipping process without the appearance of white space.
    Help me, how will it will be solved?

Leave a comment

Standard Login

Options:

Colors

  • boney m songs free download rasputin
  • cant download bully xbox 360
  • cd carla bruni download gratis
  • atlas de histologia ross download
  • calendario seria a download
  • brother mfc 7340 ocr software download
  • canon pixma mg5250 treiber download chip
  • chica boom download free mp3
  • cadillacs and dinosaurs download free game
  • 3com 3c905b tx driver download windows 7
  • adobe reader 7 vista download
  • blue best in me video download
  • b.a.p no mercy download link
  • cd the rasmus 2012 download
  • aval appadithan songs download free
  • blackbirds linkin park download free
  • cavalieri dello zodiaco hd download
  • canon mp190 driver download windows vista
  • asrock alivenf6p vsta drivers download
  • 4shared download game gratis
  • clive cussler crescent dawn download
  • americko rvanje 2012 igrica download
  • cassidy the hustla album download
  • 50 tyson icy download mp3
  • american uncial font download
  • a data s596 firmware download
  • badi assad mp3 download
  • castillos de hielo 1978 download
  • alan carr smoking download
  • canon powershot download pictures computer
  • chovendo hamburguer download rmvb
  • a primate's memoir download ebook
  • bruce almighty download full movie
  • celeron sound driver free download
  • aggressive audio mp3 download
  • 4shared download justin bieber boyfriend
  • biostar t series download
  • clock tick tock sound download
  • brides of wildcat county download
  • bhajan mp3 songs download free
  • a irmandade do anel download legendado
  • avem acelasi sange download
  • atozmp3 free download songs telugu
  • c 3.0 in a nutshell eisner download
  • clap your hand mp3 download
  • a4tech pk 935 download
  • a terceira onda rally download
  • adam smith riqueza naAAes download
  • chite suit mp3 download
  • auto installer deluxe 4.4 download
  • chasing pavements download free mp3
  • cd cid moreira download gratis
  • camper one more time download song
  • chris cornell sunshower download mp3
  • caAadores de dragAes filme download
  • akai professional lpk25 software download
  • arirang folk song download
  • aAo viejo download mp3
  • 13599 update download usb
  • an cafe maple gunman download mp3
  • casper one last wish download
  • a cabana da floresta download legendado
  • cd maria bethania perfil download
  • c3510 corby pop themes download
  • change windows xp key tool download
  • choplifter nes rom download
  • am pm christina milian mp3 download
  • can you download newgrounds videos
  • canon pixma mp500 manual download
  • club dj software download
  • ati catalyst 11.6 download windows 7
  • arma 2 pc download free
  • b2k the remixes download
  • canon mp600 software download windows 7
  • bokutachi no after school download
  • canon pixma mg6150 software download
  • children abcd learning download
  • chemistry principles zumdahl free download
  • a outra face download legendado
  • canzone europei 2012 download
  • circus theme song download
  • apprentice season 7 download
  • a estrada download legendado rmvb
  • canon mp550 treiber download
  • badla jatti da movie download
  • besos de amor mp3 download
  • 2 chainz crack slowed download
  • atozmp3 net telugu download
  • camhack gta iv download
  • city cars mod pack v1.1 download
  • banco de dados northwind download access
  • ai wa takaramono single download
  • asus k8v mx bios free download
  • black snake moan album download
  • barbra streisand concert download
  • as A?ltimas quatro coisas download palsey
  • animal crossing wild world download ita nds
  • 2310 rm 189 flash file download
  • baby i'ma liar mp3 download
  • chennai map download for android
  • bitza nopti albe download fileshare
  • channa ve ghar aaja download free
  • assassin the upcoming terror download
  • alcatel ot 800 flash file download
  • a4tech model pk 7mar free download
  • businessman mp3 songs free download ziddu
  • ambani & sons ebook download
  • angel y khriz showtime download
  • cinema 4d r 13 download free
  • cbse class 10 english textbook download
  • blur fast track gameplay download
  • a s i a h jamil mp3 free download
  • chor machaye shor songs download pk
  • cirque du soleil varekai download
  • 457 visa application form download
  • 1112 episode 2 download ipa
  • bob seger free download songs
  • albertus extra bold download free
  • autotune t pain download
  • chico buarque vida download blogspot
  • burmese for beginners download
  • blotter mac app download
  • alienware darkstar wmp download
  • annotated chess games free download
  • canon lbp 3000 free download windows 7
  • animal crossing wild world download deutsch
  • aficio mp 3350 driver download
  • arrietty's song japanese version download
  • asus m2a mx drivers free download
  • abraAo do noivo download gratis
  • cancion para mi hija download
  • 535 one piece download
  • bulletproof foamo remix download
  • chasing the sun mp3 download 320kbps
  • boni i mr juve download mp3
  • aumentare download emule adunanza
  • asrock fsb 1333 driver download
  • armin van buuren unforgivable download fisierul meu
  • 4shared download adele set fire to the rain
  • aji mu shrabani mp3 download
  • anda calugareanu o portocala download mp3
  • blackberry 7520 driver download
  • batalha espiritual livro download
  • chAopaki na ibizie rmvb download
  • aprendendo a tocar violA?o download gratis
  • alberto del rio entrance download
  • 007 facebook hack v 3.0 download
  • abc cubes game download
  • canon sx210 is download
  • box o poderoso chefA?o download
  • bA?g zemsty download pl
  • akshara lori mp3 download
  • call me maybe mp3 download 4shared.com
  • ashmit patel mms full download
  • blackberry 8700 gps download
  • brian joo unveiled mp3 download
  • canon mx700 driver download for mac
  • battleship movie download youtube
  • bruxa de blair dublado download
  • c5 05 nokia pc suite download
  • c5 05 nokia pc suite download
  • badnaam raj brar mp3 download
  • bodas de sangre download pelicula
  • apostila stm download gratis
  • bloodbath in paradise download
  • adriano celentano soli download mp3
  • belinda carlisle la luna download mp3
  • clap dem thighs mp3 download
  • cd oktoberfest download 2010
  • bandhan bengali movie download
  • appsc polytechnic lecturers hall tickets download
  • canon mx320 treiber download windows 7
  • cinematic orchestra ma fleur download blogspot
  • angry birds download completo telemovel
  • a is for alibi download saitek
  • cara download movie syok.org
  • 4084 movie songs free download