VOOZH about

URL: https://www.geeksforgeeks.org/kotlin/dynamic-imageswitcher-in-kotlin/

⇱ Dynamic ImageSwitcher in Kotlin - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Dynamic ImageSwitcher in Kotlin

Last Updated : 9 Feb, 2025

Android ImageSwitcher is a user interface widget that provides a smooth transition animation effect to the images while switching between them to display in the view. ImageSwitcher is subclass of View Switcher which is used to animates one image and displays next one. Here, we create ImageSwitcher programmatically in Kotlin file.

Steps of Implementing a Dynamic ImageSwitcher

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 Views Activity > Next > Finish.

Step 2: Modify activity_main.xml file

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

activity_main.xml:


Step 3: Create ImageSwitcher in MainActivity.kt file

Different methods of ImageSwitcher widget:

  • setImageDrawable: It is used to set a new drawable on the next ImageView in the switcher.
  • setImageResource: It is used to set a new image on the ImageSwitcher with the given resource id.
  • 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.orange,
R.drawable.guava
)

then, we create the ImageSwitcher in the MainActivity.kt file and set ImageView to display the image.

val imgSwitcher = ImageSwitcher(this)

imgSwitcher.setFactory({
val imgView = ImageView(applicationContext)
imgView.scaleType = ImageView.ScaleType.FIT_CENTER
imgView.setPadding(20, 20, 20, 20)
imgView
})

Also, we should add the ImageSwitcher to the layout using.

val layout: ConstraintLayout = findViewById(R.id.main)
layout.addView(imgSwitcher)

MainActivity.kt:

Output:

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


Comment
Article Tags:

Explore