Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Mobile / Android

Android: ViewFlipper Touch Animation like News & Weather

4.14/5 (14 votes)
30 Mar 2010CPOL6 min read 1  
Android: ViewFlipper Touch Animation like News & Weather

Introduction

In thie tutorial we can learn how to solve a common problem in Android project, to have more info regarding Android project I suggest to you to download the ADT Android Pluglins and Eclipse. Let's start with a little basics around Android development.

Background

To begin the android develompent you need tree important thins: The Android Sdk (you can download it here), A Project Editor (i suggest eclipse) and the Android eclipse plugin.

When you have the environment ready you can start with this tutorial.

When you open for the first time the Android SDK you need to create a virtual device, I suggest to create a common device using as Target the Android 1.6 Api Level 4 and then you need to add the hardware features that you need in your environment, for example: SD Card Support, Accellerometer, Camera Support etc. if you need help to start up an android virtual device follow this link.

Start the Ecplise Project

Follow these simple step to create an Android Project in eclipse:

  1. Select File > New > Project.
  2. Select Android > Android Project, and click Next.
  3. Select the contents for the project:
    • Enter a Project Name. This will be the name of the folder where your project is created.
    • Under Contents, select Create new project in workspace. Select your project workspace location.
    • Under Target, select an Android target to be used as the project's Build Target. The Build Target specifies which Android platform you'd like your application built against.

      Unless you know that you'll be using new APIs introduced in the latest SDK, you should select a target with the lowest platform version possible, such as Android 1.6.

      Note: You can change your the Build Target for your project at any time: Right-click the project in the Package Explorer, select Properties, select Android and then check the desired Project Target.

    • Under Properties, fill in all necessary fields.
      • Enter an Application name. This is the human-readable title for your application — the name that will appear on the Android device.
      • Enter a Package name. This is the package namespace (following the same rules as for packages in the Java programming language) where all your source code will reside.
      • Select Create Activity (optional, of course, but common) and enter a name for your main Activity class.
      • Enter a Min SDK Version. This is an integer that indicates the minimum API Level required to properly run your application. Entering this here automatically sets the minSdkVersion attribute in the <uses-sdk> of your Android Manifest file. If you're unsure of the appropriate API Level to use, copy the API Level listed for the Build Target you selected in the Target tab.
  4. Click Finish.
when you are ready the ADT creates for you the following folders and files:
  • src/: Includes any Activity Java file. All other Java files for your application go here.
  • <Android Version>: Includes the android.jar file that your application will build against. This is determined by the build target that you have chosen in the New Project Wizard
  • gen/: This contains the Java files generated by ADT, such as your R.java file and interfaces created from AIDL files (this is an automatic class)..
  • assets/: This is empty. You can use it to store raw asset files.
  • res/: A folder for your application resources, such as drawable files, layout files, string values, etc.
  • AndroidManifest.xml: The Android Manifest for your project.
  • default.properties: This file contains project settings, such as the build target. This files is integral to the project, as such, it should be maintained in a Source Revision Control system. It should never be edited manually — to edit project properties, right-click the project folder and select "Properties".

In this tutorial we use only two folder: src/ and res/, now start with the sample solution to the common problem

How to Slide Two (or more) Layout like the News & Weather by Touch Event

Now that you are ready with Android, one of the first things we try to in Android development is to emulate the graphics effect that have the best applications. So, one of the animations/events mostly used and highly effective is the sliding window from one activity to another by using the fing. To do this we need a little bit of java code and some tips in our XML layout.

Begin from the XML Layout File

Open from res/layout/ the main.xml (or some other layout file) and put this lines: 

XML
<ViewFlipper
    android:layout_margin="6dip"
    android:id="@+id/layoutswitcher"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView
            android:layout_height="wrap_content"
            android:id="@+id/firstpanel"
            android:paddingTop="10dip"
            android:text="my first panel"
            android:layout_width="fill_parent"
            android:layout_weight="1"
            android:textStyle="bold" >
        </TextView>
    </LinearLayout>
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView
            android:layout_height="wrap_content"
            android:id="@+id/secondpanel"
            android:paddingTop="10dip"
            android:text="my second panel"
            android:layout_width="fill_parent"
            android:layout_weight="1"
            android:textStyle="bold" >
        </TextView>
    </LinearLayout>
</ViewFlipper>

As you can see, I add one ViewFlipper, two LinearLayout and for each inner layout a simpletextview, this first step is ncessary to create a proper switching layout, after you can customize as you want the style of the two inner layout and if you want add a toolbar to switch around the inner layout.

Second step: Java Code (Switch Layout by Touch) 

Now open your main class from src/<yout package name> and in the begin of the class declare these two variables: 

Java
private ViewFlipper vf;
private float oldTouchValue;

The first Variable (VF) is needed to constrol the ViewFlipper and the second one is needed to the touch event, now attach the viewflipper to the class :

Java
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   ....
   vf = (ViewFlipper) findViewById(R.id.switchlayout);
}

Now we have a declared viewflipper and can proceed to the last step of this simple tutorial.

The Touch Event

One of the most important feature of this new mobile phone is the Touch Screen system and like iPhone apps or other touching device the user prefer to switch among the activies by their fingers. In Android develpment to attach a touch event you can do two things "implement the touchlistener" or declare am onTouchEvent by overriding the main method.

In this sample we use the second case, take a look of the following code and then to the explaination:

Java
@Override
public boolean onTouchEvent(MotionEvent touchevent) {
    switch (touchevent.getAction())
    {
        case MotionEvent.ACTION_DOWN:
        {
            oldTouchValue = touchevent.getX();
            break;
        }
        case MotionEvent.ACTION_UP:
        {
            if(this.searchOk==false) return false;
            float currentX = touchevent.getX();
            if (oldTouchValue < currentX)
            {
                vf.setInAnimation(AnimationHelper.inFromLeftAnimation());
                vf.setOutAnimation(AnimationHelper.outToRightAnimation());
                vf.showNext();
            }
            if (oldTouchValue > currentX)
            {
                vf.setInAnimation(AnimationHelper.inFromRightAnimation());
                vf.setOutAnimation(AnimationHelper.outToLeftAnimation());
                vf.showPrevious();
            }
        break;
        }
    }
    return false;
}

As you can see, when the user touch for the first time the device a fill the float variable (oldTouchValue) with the X position of his finger, then when the user release his finger I check the new position of the event to decide if the user want to go next or previous ( oldTouchValue < currentX, oldTouchValue > currentX). To change the layout the code is the same but I use different animation if the user want to go next or previous, for more explaining about the animation and the AnimationHelper I put this sample code:

Java
//for the previous movement
public static Animation inFromRightAnimation() {

    Animation inFromRight = new TranslateAnimation(
    Animation.RELATIVE_TO_PARENT,  +1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
    Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
    );
    inFromRight.setDuration(350);
    inFromRight.setInterpolator(new AccelerateInterpolator());
    return inFromRight;
    }
public static Animation outToLeftAnimation() {
    Animation outtoLeft = new TranslateAnimation(
     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  -1.0f,
     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
    );
    outtoLeft.setDuration(350);
    outtoLeft.setInterpolator(new AccelerateInterpolator());
    return outtoLeft;
    }
// for the next movement
public static Animation inFromLeftAnimation() {
    Animation inFromLeft = new TranslateAnimation(
    Animation.RELATIVE_TO_PARENT,  -1.0f, Animation.RELATIVE_TO_PARENT,  0.0f,
    Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
    );
    inFromLeft.setDuration(350);
    inFromLeft.setInterpolator(new AccelerateInterpolator());
    return inFromLeft;
    }
public static Animation outToRightAnimation() {
    Animation outtoRight = new TranslateAnimation(
     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,  +1.0f,
     Animation.RELATIVE_TO_PARENT,  0.0f, Animation.RELATIVE_TO_PARENT,   0.0f
    );
    outtoRight.setDuration(350);
    outtoRight.setInterpolator(new AccelerateInterpolator());
    return outtoRight;
    }

You can decide to put these method in a static class (like me) or to declare they in your class.

Conclusion

Now you have the base class and the event to catch the touch movement from right to left ( show.previous) and from left to right ( show.next), a simple code that explain the four animation movement amd a simple layout to try this. I would suggest to do further testing with more than two layout and with more complex content. This is only a sample of the Android ability, but I think that you can find more powerful solutions!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)