Recipe 3.8 Animating the Changing of Images Using the ImageSwitcher

Android Versions
Level 1 and above
Permissions
None
Source Code to Download from Wrox.com
ImageSwitcher.zip

The previous recipe demonstrated how to use the Gallery together with an ImageView to display a series of thumbnail images so that when one is selected, it is displayed in the ImageView. However, rather than have an image appear abruptly when the user selects it in the Gallery, you might, for example, want to apply some animation to the images so that they can transition smoothly from one image to another. In this case, you need to use the ImageSwitcher together with the Gallery.

Solution

Like the previous recipe, this example assumes you have a series of images in the res/drawable-mdpi folder (see Figure 3-18).

Create an XML file named attrs.xml and store it in the res/values folder (see Figure 3-19).

The content of the attrs.xml file is as follows:

<resources>
    <declare-styleable name="MyGallery">
        <attr name="android:galleryItemBackground" />
    </declare-styleable>   
</resources>

Add the <ImageSwitcher> and <Gallery> elements to the UI, such as the activity_main.xml file:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" ...

Get Android Application Development Cookbook: 93 Recipes for Building Winning Apps now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.