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. Sundeep
    December 16, 2012 at 11:07

    I am not getting any animation in my emulator.
    And what changes has to be made in Manifest file?

  37. 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?

  38. Landscaping The Woodlands TX
    May 21, 2013 at 14:38

    I have been browsing online more than three hours today, yet
    I never found any interesting article like yours.
    It is pretty worth enough for me. In my view, if all site owners and bloggers made good content as you did,
    the internet will be much more useful than ever before.

Leave a comment

Standard Login

Options:

Colors

  • o todo poderoso download baixaki
  • download sims 3 expansion packs online
  • van coke kartel download free mp3
  • gramps morgan album download
  • download option file pes 6 isl terbaru
  • ellie goulding download be mine
  • maroon 5 misery download video
  • download blue foundation life of a ghost
  • sonar notification download
  • cima f2 free download
  • snapbacks and tattoos remix download mp3
  • moves like jagger mp3 download 320kbps
  • nokia 2690 download photos
  • download package dependencies
  • download dragon ball ultimate battle 22
  • 2010 free download microsoft word
  • download talking parrot for nokia 5233
  • download anang feat aurel
  • download acapella rick ross
  • download linkedin for blackberry 9780
  • pergilah sepi download free
  • download rainha betsy
  • hunter hayes download free
  • lynyrd skynyrd download album
  • papi sanchez enamorame download
  • 2719400317
  • download juice itc font free
  • download git new workdir
  • iron man 3 download game
  • download lagu erie susan jangan dekati aku
  • phoenix lasso mp3 download
  • energy bliss visualization download
  • drools 4.0 download
  • download liga inggris
  • download tutorial sqlyog
  • hangover 2 download piratatuga
  • free download pcdj software full version
  • january tuesday our jewel download
  • popcorn song hot butter download
  • download rocket man the definitive hits
  • download filme corinthians 100 anos
  • shuttle bound meadowed isle download
  • amanecer parte 1 download subtitulada
  • download miễn phí yahoo messenger
  • download uncle tom's cabin by harriet beecher stowe
  • currency rate download free
  • drupal download database
  • statement form download
  • paczka mp3 download 2012
  • awarapan movie download 3gp format
  • after effects 5 download
  • bari arakeel download mp3
  • fifa 05 download full version pc free
  • netbeans 6.5 1 download
  • abba instrumental download free
  • unknown devices download windows 7
  • kat deluna download mp3
  • download chocolate with nuts
  • download pokemon diamante visual boy advance
  • streets of rage 2 download pc
  • download mirc untuk mobile
  • download koleksi lagu spin
  • ios 6 ipad 3 download chip
  • download anatomia em radiologia e tomografia
  • stoned mp3 download
  • download homepage metin2
  • must download films
  • download susan kay phantom
  • hana ringtone download
  • download pervasive 2000
  • ar eddy bear download
  • download mkvmerge per mac
  • download sme server 7.6
  • download naruto shippuden 130 sub indo
  • hef ft major gone download
  • download bre sempurna
  • horrible histories series 1 download
  • 1640 printer driver download
  • download for 300 violin orchestra
  • movie download hollywood in hindi
  • 4914947832
  • download challan 281 in excel format
  • download free bend it like beckham songs mp3
  • download abc 4 kids workshop free
  • chipset zero red-o-matic download
  • cso wallhack 2012 download
  • nfs 3 tracks download
  • download videos gangnam style
  • 1853085656
  • cheloo sau download fisierul meu
  • 100 love 3gp download
  • osthi mp3 songs free download zip
  • impossibile download file da internet
  • download dansk stavekontrol word 2010
  • eve client download
  • urdu joomla download
  • download student office 2010
  • download soft logitech pro 9000
  • sofer stam font download
  • download sharepoint 2010 nuggets
  • alegria en fundita download
  • nhpc admit card download trainee exam
  • unic remaja download
  • download psp harvest moon hero of the leaf valley
  • galaxy tab to download mode
  • download pb web launcher
  • frog's theme chrono trigger download
  • cometbird download for mac
  • download roberto carlos emoções
  • cdz ultimate cosmo mugen download
  • download dust frank ocean mp3
  • oracle companion 10g download
  • unison square garden orion download
  • free download robo video songs in telugu
  • siti download musica yahoo
  • jr dread jogi download
  • atmosphere deluxe 7.1 download
  • download traffic travis free
  • cannibal musical download
  • download dark go locker theme
  • download chris rene young homie
  • bücher download media markt
  • download singam movie of ajay devgan
  • download zawgyi unicode for mac
  • basler ip finder download
  • caindo na estrada download dublado rmvb
  • download brandy who i am
  • download zelda oot music
  • minecraft download kostenlos vollversion
  • download po form
  • download kreayshawn like it or love it
  • download pokedex alle 493 pokemon
  • download ichigo vs ulquiorra 3gp
  • bukkit 1.4.6 update download
  • ibm viavoice crack download
  • download barbie moda e magia rmvb
  • download khia been a bad girl
  • download internet tv & radio player
  • download hand history
  • download bittersweet within temptation
  • cad download eaton
  • download craft bukkit server 1.2.5
  • download logon changer for windows 7 free
  • download tranda la lume din nou
  • download full crypt raider
  • download bộ sách đĩa effortless english
  • rtpn aftershock download
  • lock up preet harpal download free
  • csd teach me dougie download
  • download epic rap battles of history cleopatra
  • 12 sky download failed
  • download mockingbird song eminem
  • download uso står her endnu
  • kindle 3g download
  • download free kp500 themes
  • surya s o krishnan songs download telugu
  • lgb 1.42 download
  • download vanilla bf2
  • wcw songs download
  • download meus dias no cairo
  • download chat yahoo dtdd
  • surface byte tags download
  • download program bandoo
  • v -station vst download
  • to reach you download anja
  • sky falls down download
  • lucky download jason mraz free
  • lineage 2 hellbound download gamershell
  • download pat martino linear expressions
  • download basic bbm
  • como fazer download no wareztuga
  • download bes 5.0 sp2
  • download fifa 06 tieng viet
  • download goa song lyrics
  • download berliner philharmoniker digital concert hall
  • nestle ice cream logo download
  • download albums lil wayne
  • tabel nrc pakan download
  • download echo360 presentation
  • download narcisa mi-e greu fara tine
  • starter boys noize download
  • unity for justice download
  • flashing cursor download
  • sketchflow styles download
  • for today breaker download blogspot
  • bitter virgin english download
  • sermons paul washer download
  • opm download websites
  • filezilla download windows 7 client
  • cyberlink youcam download effects
  • criminal minds download season 5 free
  • n ball free download chip
  • canon lide 200 download mac
  • 1429667032
  • download shades by sterling knight
  • download foxit latest version
  • dsl download zu langsam
  • bus download bus simulator
  • firefly driver download
  • download ost sherlock holmes 2009
  • 7793823032
  • download todo cambia mercedes sosa
  • free download video gurbani shabads
  • download speeds are really slow
  • pillar open your eyes download
  • hoodie allen leap year download datpiff
  • rm 505 n97 download
  • download smb all stars blur
  • mirror writing jamie woon download 320
  • download fring uiq
  • which itunes download for windows 7 64 bit
  • parrot ls 3200 download
  • download lagu cinta itu buta gratis
  • street legal redline crack download
  • download facebook hack attack 5.1
  • download segredos de uma novela
  • download ss501 snow prince mp3
  • sobi2 v card template download
  • download thai english dictionary free
  • download zindagi gulzar hai ost mp3
  • plans death cab download
  • muppets party cruise ps2 download
  • download mtp samsung galaxy
  • download nba 2k13 save game editor
  • goods delivery note template download
  • level d 767 download
  • purple rain download jailbreak
  • shoutcast dans 1.9.8 download
  • 6854947155
  • download dane cook comedy free
  • download playback lazaro um sentimento novo
  • download be calm
  • download buku awaken the giant within
  • download war commander cheat tool v1.02 exe
  • javascript disable download
  • wine encyclopedia download
  • download brush adobe photoshop cs
  • freepbx framework module download
  • dança com tudo download mp3
  • siti download basi musicali
  • mario kart pj64 download
  • skype 2.7 version download
  • winbox download now
  • dban disc download
  • tiara mp3 free download
  • download latest networking software
  • download allah wallpaper
  • download amrita rao
  • fried green tomatoes ost download
  • download de pequena sereia 2
  • download malicia segunda temporada
  • leonardo da vinci biography download
  • download trinh duyet internet explorer 8.0
  • limite vertical download dublado rmvb
  • download odbc gratis
  • gpu tweak utility download
  • download patch idm 519
  • download xlive update gta iv
  • download ideal lite
  • siam shade tribute download album
  • 3d warehouse download button missing
  • dee winamp download
  • cocoa system download
  • 7zip download org
  • act practice exam download
  • bake sale album download
  • my morning download wxpn
  • download app nokia 5800
  • download launcher for android 2.3
  • is 20gb download limit enough
  • xp boot screens download free
  • download file palette lmp
  • free download immigrant song led zeppelin mp3
  • download fashion design world
  • download cancer bats birthing the giant
  • download brick breaker revolution for mobile
  • download este habana - zumba mp3
  • heroes lore 3 download 240x320
  • desenhos dos anos 80 download
  • download sou seu fã numero 1
  • download installshield for visual studio
  • free download of spin and win game
  • ikm java test download
  • buddha hoga tera baap download
  • free download of asianet theme music
  • download honeycomb for notion ink
  • download sat nav for laptop
  • icarly iscream on halloween download
  • gilberto gil unplugged download free
  • deconstruction devin townsend project download
  • new star soccer download iphone
  • 9250066150
  • mozilla firefox download quickly
  • grenade alexa goddard mp3 download
  • powerdirector 10 tutorial book download
  • lagu lagu asli melayu download
  • download anomaly warzone earth
  • download villa free movies
  • download zro straight profit
  • download game shark 5 iso
  • 8261466772
  • halo loop 3 download
  • download seus satio
  • download zotac firestorm vga
  • download athena nu than chien tranh
  • william boyd download
  • download class actress bienvenue
  • zedd clarity extended download
  • custom story download amnesia dark descent
  • rush hour 720p download
  • never scared bonecrusher download mp3
  • download swizz beatz million bucks
  • lili creator download
  • download cruisin d'angelo
  • download on screen russian keyboard