NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

Loading...
x

Thursday, 20 May 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:

<Gallery
      android:id="@+id/Gallery01"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"></Gallery>
<ImageSwitcher
      android:id="@+id/ImageSwitcher01"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
</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 {

and
      @Override
      public View makeView() {
            ImageView iView = new ImageView(this);
            iView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            iView.setLayoutParams(new
                        ImageSwitcher.LayoutParams(
                                    LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
            iView.setBackgroundColor(0xFF000000);
            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(R.id.ImageSwitcher01);
            iSwitcher.setFactory(this);
            iSwitcher.setInAnimation(AnimationUtils.loadAnimation(this,
                        android.R.anim.fade_in));
            iSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this,
                        android.R.anim.fade_out));

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() {

                  @Override
                  public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                        iSwitcher.setImageResource(pics[arg2]);
                  }
            });
      }

36 comments:

  1. i saw yr profile Mmm very nice ..then congrat's to u..i m initial stage Android platform .so please help to me . how to get particular contact list from default layout to list layout madam..

    ReplyDelete
  2. Thanks a lot Sai. That was very helpful as it was described nicely. Cheers.

    ReplyDelete
  3. Excellent post, thank you very much!

    ReplyDelete
  4. really , it's wonderful topic you have given. i have the same requirement but, i need scroll the images dynamically on top. i dont want click or touch the screen. some body help me.

    ReplyDelete
    Replies
    1. good tute.......

      Delete
  5. Sai, How would you implement something like this as a book? So the images 'flip' with a swipe of the finger. Similar to ebook readers changing pages. I'm just learning how to develop for Android and haven't been able to find a good example. Any help would be greatly appreciated.
    -Pav

    ReplyDelete
  6. The link to the Gallery Example points to www.blogger.com

    ReplyDelete
    Replies
    1. Indeed. Should be to

      saigeethamn.blogspot.com/2010/05/gallery-view-android-developer-tutorial.html

      I think...

      Delete
  7. thanks i have requ to develop this

    Laxmi

    ReplyDelete
  8. Worth reading article.
    BTW, can you tell me how to make this ImageSwitcher transparent instead of black? I try to set its background to FF000000 but it doesn't work.

    ReplyDelete
    Replies
    1. Hello :) I am newbie in android development and I read this article. I am also wondering how can I make the ImageSwitcher transparent. Can I ask if you already found a solution? Thanks! I really need this for a project. Thanks Again!

      Delete
  9. Good Example for beginner
    i suggest to add comments in your example that why particular class is used to implement particular feature/service in example so developer can also gain basic fundamental knowledge of various types of class and interface in android.
    i suggest you because it is very painful to search for use of class/function/interface used in example

    ReplyDelete
  10. i have over 400 images. and this setup seems to work good but when i slide through the imageswitcher after a short while it shows all black
    if i click through each individually it works fine

    any suggestions?

    ReplyDelete
  11. hey thanks....it helped me
    it will be much better if u add touch event for all the things

    ReplyDelete
  12. how about to use setImageURI ?
    example :

    Uri imagePath = Uri.parse("android.resource://com.plugie.tpa/drawable/q1_1");
    questionImageSwitcher.setImageURI(imagePath);

    ReplyDelete
  13. Hi, Thanks very much for your code snippets. Im concerned that every image is loaded as a new ImageView. Can you make an ammendment to your code to show how to clear old views or work more efficiently. I get out of memory issues with the above code. Thank you.

    ReplyDelete
  14. you could reuse the ImageViews used in the gallery... something like this:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    ImageView img;
    if(convertView==null) {
    img = new ImageView(mContext);
    img.setImageResource(mImageIds[position]);
    img.setLayoutParams(new Gallery.LayoutParams(150, 100));
    img.setScaleType(ScaleType.FIT_XY);
    img.setBackgroundResource(mGalleryItemBackground);
    } else {
    img = (ImageView) convertView;
    }

    return img;
    }

    ReplyDelete
  15. Only four animations are working. they are: fade_in,fade_out, slide_in_left, slide_out_right remaining animations are not working. Emulator is displaying an error message to forceStop. Why is this happening and what is the solution

    ReplyDelete
  16. Very helpful, thanks for taking the time to post this.

    ReplyDelete
  17. Hi... Thanks alot! :) It is very helpful...

    ReplyDelete
  18. nice one..but i have to set as wallpaper..how i will do that..please help me out

    ReplyDelete
  19. @ganesh: The piece of code given below will set the currently viewed image as wallpaper.
    Bitmap temp = null;
    Gallery gallery = (Gallery) findViewById(R.id.photogallery);
    currentPos = gallery.getSelectedItemPosition();
    temp = pics.get(currentPos);
    WallpaperManager wm = WallpaperManager.getInstance(this);
    if (temp != null) {
    try {
    wm.setBitmap(temp);
    } catch (IOException e) {
    e.printStackTrace();
    }

    ReplyDelete
  20. Greetings Ma'am!
    Nice post from you..Can you help me if i want to use Button to changes the image rather than changing and selecting from Gallery view.

    Thanks in advance

    ReplyDelete
  21. HIIII...Your tutorials really awesome .I am getting a problem in Gallery view because in your tutorial it is static when i am working in dynamic way that is rendering images from server how can i get images to Gallery ... from server their are string values when we call the image i need to use the string not int values for that what i need to do how can i change the string values to int values to render the images from server ?????if u know pls share it ....

    Thks in advance...

    ReplyDelete
  22. for setting wallpaper jst do:
    public void onItemClick(AdapterView arg0, View arg1, int arg2,
    long arg3) {
    iSwitcher.setImageResource(pics[arg2]);
    Bitmap bmp=BitmapFactory.decodeStream(getResources().openRawResource(pics[arg2]));
    try {
    getApplicationContext().setWallpaper(bmp);
    } catch (IOException e)
    {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    }
    });
    }

    ReplyDelete
  23. hi mam, the imageView is animating but in the meanwhile how to animate the gallery view images since it is static while the images are animating.! So can u provide the solution ?

    ReplyDelete
  24. Hii ,, can you please help me out with an example on how to use AdapterViewFlipper in a widget

    ReplyDelete
  25. hi Can any one help me! how to display SD card images in gallery view?

    ReplyDelete
  26. Copy pasted the Android SDK sample of ImageSwitcher, please bring out something new!!!

    ReplyDelete
  27. hi sai i need a doubt to be clarified,
    as while moving the images, is there any possible to put the background image like a person or thing in the place and the locations are to be moved, if so could please help me or mail me on this...

    my mail id: bosekarthiks@gmail.com

    ReplyDelete
  28. Well done. Thank you.

    ReplyDelete
  29. this is a good example

    ReplyDelete
  30. Madam,I want take image from gallery and set image as wallpaper,how can be do this task,Please help me.

    ReplyDelete