Thursday, May 20, 2010

Image Switcher View | Android Developer Tutorial

Now we will explore ImageSwitcher View. It is a view useful to switch smoothly between two images and thus provides ways of transitioning from one to another through appropriate animations.

We will implement the same concept of showing a gallery of images that scrolls at the top of the android screen landscape and upon selection of one image, it gets displayed as a larger image in the lower part through the use of an ImageSwitcher. This is what I had done earlier in the GalleryView tutorial but now instead of showing the selected picture through an ImageView, I will show it using a ImageSwitcher. Though the output may seem very similar, lot of other methods are available on the ImageSwitcher that can be used, if required.

Here is how the output would look (NOTE that I have not used the default gallery background provided by Android in the Gallery images)

So, to begin with, first we need to declare the layout xml to have a gallery and the ImageSwitcher:


The next thing that we need to do is create a class that not only extends Activity but also implements ViewFactory. The ViewFactory is a Interface that creates views that need to be shown in the ImageSwitcher. So it has one method makeView() which we need to implement. It is here that we can set the attributes of the ImageView that would be shown within the ImageSwitcher -  like its background, it scale, its layout parameters etc. – typically those attributes that we would have otherwise statically set through a layout xml.

Here is the class declaration and the method makeView():

public class ImageSwitcherView extends Activity implements ViewFactory {

      public View makeView() {
            ImageView iView = new ImageView(this);
            return iView;
This alone is the real difference from the Gallery example.

Other smaller things we need to do is get a handle to the ImageSwitcher in the onCreate() method:

            iSwitcher = (ImageSwitcher) findViewById(;

Here we also set the animation on how the image should fly in and fly out of the area. Then, we get a handle to the gallery and set an ImageAdapter to it. The ImageAdpater is as described in my Gallery Example. If you have not seen that, please go through that and then try this example, as I would not want to repeat myself here.
Now on the click of a gallery image, we would want to pass the selected image to the ImageSwitcher and this is what we do here:

            gallery.setOnItemClickListener(new OnItemClickListener() {

                  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

No comments:

Post a Comment