VOOZH about

URL: https://www.geeksforgeeks.org/android/image-switcher-in-android-with-example/

⇱ Image Switcher in Android with Example - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Image Switcher in Android with Example

Last Updated : 17 Feb, 2025

Sometimes, you may not want an image to appear suddenly on the screen. Instead, you might prefer a smooth transition from one image to another using animation. Android offers a tool called ImageSwitcher to help with this. An ImageSwitcher lets you add simple transition effects to your images.

What are we going to build?

In this article, we'll create an app where you can swipe images from left to right (and vice versa) using buttons. As you swipe, the ImageSwitcher will animate the change between images.

Step 1: Create a new project in Android Studio

First we create a new project by following the below steps: 

  • Click on File, then New > New Project.
  • After that include the Kotlin support and click on next.
  • Select the minimum SDK as per convenience and click next button.
  • Then select the Empty activity > next > finish.

We are going to implement this project using both Java and Kotlin.

Step 2: Modify activity_main.xml file

In this file, we use constraint layout with ImageSwitcher and Buttons.

activity_main.xml:

Design UI:

👁 Image

Step 3: Access ImageSwitcher in MainActivity file

Different methods of ImageSwitcher widget:

  1. setImageDrawable: It is used to set a new drawable on the next ImageView in the switcher.
  2. setImageResource: It is used to set a new image on the ImageSwitcher with the given resource id.
  3. setImageURI: It is used to set a new image on the ImageSwitcher with the given URI.

First, we declare an array which contains the resource of the images used for the ImageView. 

private val array = intArrayOf(R.drawable.grape, R.drawable.guava, R.drawable.orange)

then, we access the ImageSwitcher from the XML layout and set ImageView to display the image. 

val imgSwitcher: ImageSwitcher = findViewById(R.id.imageSwitcher)
imgSwitcher.setFactory({
 val imgView = ImageView(applicationContext)
 imgView.scaleType = ImageView.ScaleType.FIT_CENTER
 imgView.setPadding(8, 8, 8, 8)
 imgView
})

Also, we will use one of the above method for ImageSwitcher. 

imgSwitcher.setImageResource(array[index])

MainActivity file:

Output:

Click next button then we get the other animated image in the View. 


Comment
Article Tags:

Explore