DEV Community

Md Nazmul Islam
Md Nazmul Islam

Posted on

How to switch the image on Android?

Sometimes you don't want an image to appear abruptly on the screen, rather you want to apply some kind of animation to the image when it transitions from one image to another. This is supported by android in the form of ImageSwitcher.

An image switcher allows you to add some transitions on the images through the way they appear on screen. In order to use image Switcher, you need to define its XML component first. Its syntax is given below −

android:id="@+id/imageSwitcher1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" >

Now we create an intance of ImageSwithcer in java file and get a reference of this XML component. Its syntax is given below −

private ImageSwitcher imageSwitcher;
imageSwitcher = (ImageSwitcher)findViewById(R.id.imageSwitcher1);
The next thing we need to do implement the ViewFactory interface and implement unimplemented method that returns an imageView. Its syntax is below −

imageSwitcher.setImageResource(R.drawable.ic_launcher);
imageSwitcher.setFactory(new ViewFactory() {
public View makeView() {
ImageView myView = new ImageView(getApplicationContext());
return myView;
}
}
The last thing you need to do is to add Animation to the ImageSwitcher. You need to define an object of Animation class through AnimationUtilities class by calling a static method loadAnimation. Its syntax is given below −

Animation in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);

You can learn more about image switcher on android from this article: Image Switcher in Android Example Programmatically

Top comments (0)