Android ViewFlipper Using Kotlin With Example

In this article, we will learn about android ViewFlipper using Kotlin. We will go through various example that demonstrates how to use different attributes of ViewFlipper. For example,

In this article, we will get answer to questions like –

  • What is ViewFlipper?
  • Why should we consider ViewFlipper while designing ui for any app?
  • What are possibilities using ViewFlipper while designing ui? etc.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Kotlin ViewFlipper Output Android ViewFlipper Using Kotlin With Example

Tutorialwing Kotlin ViewFlipper Output

Getting Started

We can define android ViewFlipper widget as below –

ViewFlipper is a widget that are used to switch between views that have been added to it. Only one view is shown at a time. We can also set animations that will be used when view is shown / hidden.

Now, how do we use ViewFlipper in android application ?

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as ViewFlipper. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android ViewFlipper Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using ViewFlipper in Kotlin

Follow steps below to use ViewFlipper in newly created project –

  • Download Drawable Resources Needed

    We need some images, stored in res/drawable folder, that will be used in viewFlipper in the application. We can click here to download images used in the application.

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">ViewFlipper</string>
        <string name="pause">Pause</string>
        <string name="play">Play</string>
        <string name="flipping_started">Flipping Started...</string>
        <string name="flipping_stopped">Flipping Stopped...</string>
    </resources>
    
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <Button
            android:id="@+id/playPause"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="15dp"
            android:text="@string/pause"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <ViewFlipper
            android:id="@+id/viewFlipper"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:autoStart="true"
            android:flipInterval="2000"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/playPause" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    

    In activity_main.xml file, we have defined viewFlipper. Attribute android:autoStart=”” is used to set whether viewFlipper should start flipping the view automatically or not. If set true, it means it will start automatically. Attribute android:flipInterval=”” is used to set the time interval after which view will be flipped.

  • We can also access it in Kotlin File, MainActivity.kt, as below –

    package com.tutorialwing.viewflipper
    
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.view.Gravity
    import android.view.ViewGroup
    import android.widget.FrameLayout
    import android.widget.ImageView
    import android.widget.Toast
    import com.tutorialwing.viewflipper.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    	private var imageList = intArrayOf(
    		R.drawable.guava,
    		R.drawable.jackfruit,
    		R.drawable.mix_fruit,
    		R.drawable.pomegranate,
    		R.drawable.strawberry,
    		R.drawable.zespri_kiwi
    	)
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		val view = binding.root
    		setContentView(view)
    
    		setupViewFlipper()
    	}
    
    	private fun setupViewFlipper() {
    		val viewFlipper = binding.viewFlipper
    		viewFlipper.setInAnimation(applicationContext, android.R.anim.slide_in_left)
    		viewFlipper.setOutAnimation(applicationContext, android.R.anim.slide_out_right)
    
    		// Add imageView for each image to viewFlipper.
    		for (image in imageList) {
    			val imageView = ImageView(this)
    			val layoutParams = FrameLayout.LayoutParams(
    				ViewGroup.LayoutParams.MATCH_PARENT,
    				ViewGroup.LayoutParams.WRAP_CONTENT
    			)
    			layoutParams.setMargins(30, 30, 30, 30)
    			layoutParams.gravity = Gravity.CENTER
    			imageView.layoutParams = layoutParams
    			imageView.setImageResource(image)
    			viewFlipper.addView(imageView)
    		}
    
    		// set clickListener of button to play/pause viewFlipper.
    		binding.playPause.setOnClickListener {
    			if (viewFlipper.isFlipping)
    				viewFlipper.stopFlipping()
    			else
    				viewFlipper.startFlipping()
    
    			binding.playPause.text =
    				getString(if (viewFlipper.isFlipping) R.string.pause else R.string.play)
    			Toast.makeText(
    				this@MainActivity,
    				getString(if (viewFlipper.isFlipping) R.string.flipping_started else R.string.flipping_stopped),
    				Toast.LENGTH_SHORT
    			).show()
    		}
    	}
    }
    

    We have accessed viewFlipper using kotlin file (i.e. in MainActivity.kt file) in the application. Then, we have set in and out animations in it. in and out animations are used when view is shown or hidden. After that, we have created ImageView that have been added to viewFlipper. Number of imageView created are equal to length of imageList. After that, we have set click listener on viewFlipper that play/pause view flipping in viewFlipper. We have also showing a toast message that displays the current status of the viewFlipper (whether viewFlipper is flipping the view or not).

Now, run the application. We will get output as below –

Tutorialwing Kotlin ViewFlipper Output Android ViewFlipper Using Kotlin With Example

Tutorialwing Kotlin ViewFlipper Output

Different Attributes of ViewFlipper in XML

Now, we will see how to use different attributes of Android ViewFlipper using Kotlin to customise it –

Set Id of ViewFlipper

Many a time, we need id of View to access it in kotlin file or create ui relative to that view in xml file. So, we can set id of ViewFlipper using android:id attribute like below –

    <ViewFlipper
        android:id="@+id/viewFlipper_ID"
        />

Here, we have set id of ViewFlipper as viewFlipper_ID using android:id=”” attribute. So, if we need to reference this ViewFlipper, we need to use this id – viewFlipper_ID.
Learn to Set ID of ViewFlipper Dynamically

Set Width of ViewFlipper

We use android:layout_width=”” attribute to set width of ViewFlipper.
We can do it as below –

    <ViewFlipper
        android:id="@+id/viewFlipper_ID"
        android:layout_width="wrap_content"
        />

Width can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value (like 20dp, 30dp etc.).
Learn to Set Width of ViewFlipper Dynamically

Set Height of ViewFlipper

We use android:layout_height=”” attribute to set height of ViewFlipper.
We can do it as below –

    <ViewFlipper
        android:id="@+id/viewFlipper_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

Height can be either “MATCH_PARENT” or “WRAP_CONTENT” or any fixed value.
Learn to Set Height of ViewFlipper Dynamically

Set Padding of ViewFlipper

We use android:padding=”” attribute to set padding of ViewFlipper.
We can do it as below –

    <ViewFlipper
        android:id="@+id/viewFlipper_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        />

Here, we have set padding of 10dp in ViewFlipper using android:padding=”” attribute.
Learn to Set Padding of ViewFlipper Dynamically

Set Margin of ViewFlipper

We use android:layout_margin=”” attribute to set margin of ViewFlipper.
We can do it as below –

    <ViewFlipper
        android:id="@+id/viewFlipper_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        />

Here, we have set margin of 10dp in ViewFlipper using android:layout_margin=”” attribute.
Learn to Set Margin of ViewFlipper Dynamically

Set Background of ViewFlipper

We use android:background=”” attribute to set background of ViewFlipper.
We can do it as below –

    <ViewFlipper
        android:id="@+id/viewFlipper_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#ff0000"
        />

Here, we have set background of color #ff0000 in ViewFlipper using android:background=”” attribute.
Learn to Set Background of ViewFlipper Dynamically

Set Visibility of ViewFlipper

We use android:visibility=”” attribute to set visibility of ViewFlipper.
We can do it as below –

    <ViewFlipper
        android:id="@+id/viewFlipper_ID"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
        />

Here, we have set visibility of ViewFlipper using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of ViewFlipper Dynamically

Till now, we have see how to use android ViewFlipper using Kotlin. We have also gone through different attributes of ViewFlipper to perform certain task. Let’s have a look at list of such attributes and it’s related task.

Different Attributes of Android ViewFlipper Widget

Below are the various attributes that are used to customise android ViewFlipper Widget. However, you can check the complete list of attributes of ViewFlipper in it’s official documentation site. Here, we are going to list some of the important attributes of this widget –

Some of the popular attributes of android viewFlipper widget are –

Sr. XML Attributes Description
1 android:autoStart If set true, it will automatically start animating views.
2 android:flipInterval Specifies the time interval after which view will be flipped

Some of the popular attributes of android ViewFlipper inherited from ViewAnimator are –

Sr. XML Attributes Description
1 android:animateFirstView Specifies whether to animate first view when the viewAnimation is first displayed
2 android:inAnimation Specifies the animation to be used when view is shown
3 android:outAnimation Specifies the animation to be used when view is hidden

Some of the popular attributes of android ViewFlipper inherited from FrameLayout are –

Sr. XML Attributes Description
1 android:foregroundGravity Specifies the gravity of the foreground drawable
2 android:measureAllChildren Specifies whether to measure all children or only those in VISIBLE or INVISIBLE state when measuring

Some of the popular attributes of android ViewFlipper inherited from ViewGroup are –

Sr. XML Attributes Description
1 android:animateLayoutChanges Specifies whether LayoutTransition should run whenever there is any changes in layout
2 android:animationCache Specifies whether layout animations should create a drawing cache for their children.
3 android:clipToPadding Specifies whether the ViewGroup will clip its children and resize (but not clip) any EdgeEffect to its padding, if padding is not zero
4 android:layoutAnimation Specifies the layout animation to use the first time the ViewGroup is laid out
5 android:layoutMode Specifies the layout mode of this viewGroup

Some of the popular attributes of android ViewFlipper inherited from View are –

Sr. XML Attributes Description
1 android:alpha Specifies the alpha of the view
2 android:background Specifies the background of the view
3 android:backgroundTint Specifies the tint to apply to background drawable
4 android:backgroundTintMode Specifies blending mode to apply to background tint
5 android:clickable Specifies whether view is clickable or not
6 android:elevation Specifies z-depth of the view
7 android:focusable Specifies whether this view can take focus or not
8 android:foreground Specifies drawable to be used to show above this view

We have seen different attributes of ViewFlipper and how to use it. If you wish to visit post to learn more about it

Thus, we have seen what is ViewFlipper, how can we use android ViewFlipper using Kotlin ? etc. We also went through different attributes of android ViewFlipper.

Leave a Reply