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. In this article, we will take a look at How to Create a Dynamic Image Switcher in Android. A sample video is given below to get an idea about what we are going to do in this article.
Note: This Android article covered in both Java and Kotlin languages.Â
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
Step 2: Working with the activity_main.xml file
Navigate to app > res > layout > activity_main.xml and add the below code to it. Comments are added in the code to get to know in detail.Â
XML
<?xml version="1.0" encoding="utf-8"?><!--on below line we are creating our linear layout--><LinearLayout    android:id="@+id/idLLContainer"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_centerInParent="true"    android:layout_gravity="center"    android:gravity="center"    android:orientation="vertical"    tools:context=".MainActivity"></LinearLayout> |
Step 3: Working with the MainActivity fileÂ
Navigate to app > java > your app’s package name > MainActivity file and add the code below. Comments are added in the code to get to know in detail. Â
Kotlin
package com.gtappdevelopers.kotlingfgprojectÂ
import android.graphics.Typefaceimport android.os.Bundleimport android.view.ViewGroupimport android.view.animation.AnimationUtilsimport android.widget.*import androidx.appcompat.app.AppCompatActivityÂ
class MainActivity : AppCompatActivity() {Â
    // on below line creating a variable.    lateinit var containerLL: LinearLayout    val images = arrayOf(R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4)    var index = 0Â
    override fun onCreate(savedInstanceState: Bundle?) {        super.onCreate(savedInstanceState)        setContentView(R.layout.activity_main)Â
        // on below line we are initializing our variables.        containerLL = findViewById(R.id.idLLContainer)Â
        // on below line we are creating layout        // params for text view.        // and specifying width as match parent        // and height as wrap content        val txtLayoutParam = LinearLayout.LayoutParams(            ViewGroup.LayoutParams.MATCH_PARENT,            ViewGroup.LayoutParams.WRAP_CONTENT        )Â
        // on below line we are creating our dynamic text view        val headingTV = TextView(this)Â
        // on below line we are setting for our text view.        headingTV.text = "Dynamic Image Switcher in Android"Â
        // on below line we are updating text size.        headingTV.textSize = 20fÂ
        // on below line we are updating text color and font        headingTV.setTextColor(resources.getColor(R.color.black))        headingTV.typeface = Typeface.DEFAULT_BOLDÂ
        // on below line we are adding padding        headingTV.setPadding(20, 20, 20, 20)Â
        // on below line we are specifying text alignment.        headingTV.textAlignment = TextView.TEXT_ALIGNMENT_CENTERÂ
        // on below line we are adding layout        // param for heading text view.        headingTV.layoutParams = txtLayoutParamÂ
        // on below line we are creating a simple text switcher.        val imageSwitcher = ImageSwitcher(this)Â
        // on below line we are setting factor for our text switcher.        imageSwitcher.setFactory {            // on below line we are adding a image view in our image switcher.            val imageView = ImageView(this@MainActivity)            // on below line we are adding scale and padding to our image view.            imageView.scaleType = ImageView.ScaleType.FIT_CENTER            imageView.setPadding(20, 20, 20, 20)            imageView        }Â
        // on below line we are setting text for text switcher.        imageSwitcher.setImageResource(images[index])Â
        // on below line we are creating a variable        // for our slide in animation        val imageIn = AnimationUtils.loadAnimation(            this, android.R.anim.slide_in_left        )        // on below line we are setting animation        // to our text switcher.        imageSwitcher.inAnimation = imageInÂ
        // on below line we are creating a variable        // for slide out animation        val imageOut = AnimationUtils.loadAnimation(            this, android.R.anim.slide_out_right        )                 // on below line we are setting out        // animation for text switcher        imageSwitcher.outAnimation = imageOutÂ
        // on below line we are creating a layout params for button        val buttonParam = LinearLayout.LayoutParams(            ViewGroup.LayoutParams.MATCH_PARENT,            ViewGroup.LayoutParams.WRAP_CONTENT        )        // on below line we are adding margin for buttons.        buttonParam.setMargins(10, 10, 10, 10)Â
        // on below line we are creating a previous button        // and adding text and style to it on below line        val prevBtn = Button(this)        prevBtn.text = "Previous"        prevBtn.isAllCaps = false                 // on below line setting params to it.        prevBtn.layoutParams = buttonParam                 // on below line we are setting text color to it.        prevBtn.setTextColor(resources.getColor(R.color.white))                 // on below line we are adding background color to it.        prevBtn.setBackgroundColor(resources.getColor(R.color.purple_200))                 // on below line we are adding click listener        prevBtn.setOnClickListener {            // on below line we are updating index            index = if (index - 1 >= 0) index - 1 else 3            imageSwitcher.setImageResource(images[index])        }Â
        // on below line we are creating a next button        // and adding text and style to it on below line        val nextBtn = Button(this)        nextBtn.text = "Next"        nextBtn.isAllCaps = false                // on below line setting params to it.        nextBtn.layoutParams = buttonParam                 // on below line we are setting text color to it.        nextBtn.setTextColor(resources.getColor(R.color.white))                 // on below line we are adding background color to it.        nextBtn.setBackgroundColor(resources.getColor(R.color.purple_200))                 // on below line we are adding click listener        nextBtn.setOnClickListener {            // on below line we are updating index            index = if (index + 1 < images.size) index + 1 else 0            imageSwitcher.setImageResource(images[index])        }Â
        // on below line we are adding our views        // to container linear layout        containerLL.addView(headingTV)        containerLL.addView(imageSwitcher)        containerLL.addView(prevBtn)        containerLL.addView(nextBtn)Â
    }} |
Java
package com.gtappdevelopers.kotlingfgproject;Â
import android.graphics.Typeface;import android.os.Build;import android.os.Bundle;import android.view.Gravity;import android.view.View;import android.view.ViewGroup;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.Button;import android.widget.ImageSwitcher;import android.widget.ImageView;import android.widget.LinearLayout;import android.widget.TextView;import android.widget.ViewSwitcher;import androidx.annotation.RequiresApi;import androidx.appcompat.app.AppCompatActivity;Â
public class MainActivity extends AppCompatActivity {Â
    // on below line we are creating variables.    private LinearLayout containerLL;    int images[] = {R.drawable.img1, R.drawable.img2, R.drawable.img3, R.drawable.img4};    int index = 0;Â
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);Â
        // on below line we are initializing our variables.        containerLL = findViewById(R.id.idLLContainer);Â
        // on below line we are creating layout params for text view.        // and specifying width as match parent and height as wrap content        LinearLayout.LayoutParams txtLayoutParam = new LinearLayout.LayoutParams(                ViewGroup.LayoutParams.MATCH_PARENT,                ViewGroup.LayoutParams.WRAP_CONTENT        );                 // on below line we are adding gravity        txtLayoutParam.gravity = Gravity.CENTER;Â
        // on below line we are creating our dynamic text view        TextView headingTV = new TextView(this);Â
        // on below line we are setting for our text view.        headingTV.setText("Dynamic Image Switcher in Android");Â
        // on below line we are updating text size.        headingTV.setTextSize(20f);Â
        // on below line we are updating text color and font        headingTV.setTextColor(getResources().getColor(R.color.black));        headingTV.setTypeface(Typeface.DEFAULT_BOLD);Â
        // on below line we are adding padding        headingTV.setPadding(20, 20, 20, 20);Â
        // on below line we are specifying text alignment.        headingTV.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);Â
        // on below line we are adding layout param        // for heading text view.        headingTV.setLayoutParams(txtLayoutParam);Â
        // on below line we are creating a simple text switcher.        ImageSwitcher imageSwitcher = new ImageSwitcher(this);Â
        // on below line we are setting factor for our text switcher.        imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {            @Override            public View makeView() {                // on below line we are adding a image view in our image switcher.                ImageView imageView = new ImageView(MainActivity.this);                                 // on below line we are adding scale and padding to our image view.                imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);                imageView.setPadding(20, 20, 20, 20);                return imageView;            }        });Â
        // on below line we are setting text for text switcher.        imageSwitcher.setImageResource(images[index]);Â
        // on below line we are creating a variable        // for our slide in aniamtion        Animation imageIn = AnimationUtils.loadAnimation(                this, android.R.anim.slide_in_left        );                 // on below line we are setting animation        // to our text switcher.        imageSwitcher.setInAnimation(imageIn);Â
        // on below line we are creating a variable        // for slide out animation        Animation imageOut = AnimationUtils.loadAnimation(                this, android.R.anim.slide_out_right        );                 // on below line we are setting out        // animation for text switcher        imageSwitcher.setOutAnimation(imageOut);Â
        // on below line we are creating a layout params for button        LinearLayout.LayoutParams buttonParam = new LinearLayout.LayoutParams(                ViewGroup.LayoutParams.MATCH_PARENT,                ViewGroup.LayoutParams.WRAP_CONTENT        );                 // on below line we are adding margin for buttons.        buttonParam.setMargins(10, 10, 10, 10)Â
        // on below line we are creating a previous button        // and adding text and style to it on below line        Button prevBtn = new Button(this);        prevBtn.setText("Previous");        prevBtn.setAllCaps(false);                 // on below line setting params to it.        prevBtn.setLayoutParams(buttonParam);                 // on below line we are setting text color to it.        prevBtn.setTextColor(getResources().getColor(R.color.white));                 // on below line we are adding background color to it.        prevBtn.setBackgroundColor(getResources().getColor(R.color.purple_200));                 // on below line we are adding click listener        prevBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // on below line we are updating index                if (index - 1 >= 0) {                    index = index - 1;                } else {                    index = 3;                }                imageSwitcher.setImageResource(images[index]);            }        });Â
        // on below line we are creating a next button        // and adding text and style to it on below line        Button nextBtn = new Button(this);        nextBtn.setText("Next");        nextBtn.setAllCaps(false);                 // on below line setting params to it.        nextBtn.setLayoutParams(buttonParam);                 // on below line we are setting text color to it.        nextBtn.setTextColor(getResources().getColor(R.color.white));                 // on below line we are adding background color to it.        nextBtn.setBackgroundColor(getResources().getColor(R.color.purple_200));                 // on below line we are adding click listener        nextBtn.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // on below line we are updating index                if (index + 1 < images.length) {                    index = index + 1;                } else {                    index = 0;                }                imageSwitcher.setImageResource(images[index]);            }        });Â
        // on below line we are adding our views        // to container linear layout        containerLL.addView(headingTV);        containerLL.addView(imageSwitcher);        containerLL.addView(prevBtn);        containerLL.addView(nextBtn);Â
    }} |
Now run your project to see the output of the application.Â
Output:
