Android AdapterViewFlipper Programmatically in Kotlin

In this article, we will learn how to create android AdapterViewFlipper programmatically in Kotlin. We will go through various steps that explains how to create AdapterViewFlipper and add it in kotlin file, use different attributes to customise it etc. in any android application. For example, how to set text in AdapterViewFlipper programmatically, how to set id of AdapterViewFlipper, how to capitalise text of AdapterViewFlipper dynamically etc. We will get answer to all such questions in this post.

Learn to use Different Attributes of AdapterViewFlipper in XML File to Customize it.

Output

Tutorialwing Kotlin Dynamic AdapterViewFlipper Output Android AdapterViewFlipper Programmatically in Kotlin

Tutorialwing Kotlin Dynamic AdapterViewFlipper Output

Getting Started

We can define android AdapterViewFlipper widget as below –

AdapterViewFlipper is subclass of ViewFlipper that are used to switch between views using some animations. Only one view is shown at a time.

Now, how do we use AdapterViewFlipper in android application ?

Creating New Project

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 DynamicAdapterViewFlipper. 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 AdapterViewFlipper in 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.

Since we have a new project, we will modify the xml and class file to use AdapterViewFlipper programmatically in kotlin. Please follow the steps below.

2. Modify Values Folder

Open res/values/strings.xml file. Add below code into it.

<resources>
    <string name="app_name">AdapterViewFlipper</string>
    <string name="no_image">No Image</string>
</resources>

Other values folders have not been changed. So, we are not going to mention it here.

3. Download Drawable Resources Needed

We need some drawable images to create different views in AdapterViewFlipper. So, we can click here to download images to be used in the application.

4. Create Animations for AdapterViewFlipper

Now, we will define animations to be used whenever there is a transition between current view and another view (next/previous) in the application. So, Follow steps below to define the animations –

  1. Create a folder, named as animator, in main/res folder.
  2. Then, create an xml file, left_in.xml, in main/res/animator folder. Then, add below code into it.
    <objectAnimator
    	xmlns:android="http://schemas.android.com/apk/res/android"
    	android:duration="600"
    	android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    	android:propertyName="x"
    	android:valueFrom="-1500"
    	android:valueTo="0"
    	android:valueType="floatType"/>
    
  3. Then, create another xml file, right_out.xml, in main/res/animator folder. Then, add below code into it.
    <objectAnimator
    	xmlns:android="http://schemas.android.com/apk/res/android"
    	android:duration="600"
    	android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    	android:propertyName="x"
    	android:valueFrom="0"
    	android:valueTo="1500"
    	android:valueType="floatType"/>
    

5. Create View For Single Item

Now, we will crete view for single item in adapterViewFlipper. So, create an xml file, named as item.xml, in main/res/layout folder. Then, add below code into 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:contentDescription="@string/no_image"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/black"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/image" />

</androidx.constraintlayout.widget.ConstraintLayout>

6. Create an Adapter For AdapterViewFlipper

Now, we will create an adapter for adapterViewFlipper that are responsible to provide data and create view in adapterViewFlipper. So, Create a kotlin file, CustomAdapter.kt, in main/java/com.tutorialwing.dynamicadapterviewflipper folder. Then, add below code into it.

package com.tutorialwing.dynamicadapterviewflipper

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.TextView
import com.tutorialwing.dynamicadapterviewflipper.databinding.ItemBinding

class CustomAdapter internal constructor(
	context: Context,
	private val nameList: Array<String>,
	private val imageList: IntArray
) : BaseAdapter() {

	private val inflater: LayoutInflater = LayoutInflater.from(context)

	override fun getCount(): Int {
		return nameList.size
	}

	override fun getItem(position: Int): Any {
		return nameList[position]
	}

	override fun getItemId(position: Int): Long {
		return position.toLong()
	}

	override fun getView(position: Int, view: View?, parent: ViewGroup): View {
		var convertView = view
		val holder: ViewHolder
		if (convertView == null) {
			val binding = ItemBinding.inflate(inflater)
			convertView = binding.root
			holder = ViewHolder()
			holder.imageView = binding.image
			holder.name = binding.name
			convertView.tag = holder
		} else {
			holder = convertView.tag as ViewHolder
		}
		holder.name!!.text = nameList[position]
		holder.imageView!!.setBackgroundResource(imageList[position])
		return convertView
	}

	inner class ViewHolder {
		internal var imageView: ImageView? = null
		internal var name: TextView? = null
	}
}

Adapter is responsible to provide data and create view for adapterViewFlipper. getView() method is responsible to create view for a given position in adapter.

7. Modify Layout Folder

Open res/layout/activity_main.xml file. Add below code into it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:id="@+id/rootContainer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical">

</LinearLayout>

Note that LinearLayout has id rootContainer. In Kotlin file, we will create AdapterViewFlipper Dynamically and add it into this LinearLayout having id rootContainer.

8. Create Android AdapterViewFlipper programmatically in Kotlin

Open src/main/java/com.tutorialwing.dynamicadapterviewflipper/MainActivity.kt file. Then, add below code into it.

package com.tutorialwing.dynamicadapterviewflipper

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.AdapterViewFlipper
import android.widget.LinearLayout
import com.tutorialwing.dynamicadapterviewflipper.databinding.ActivityMainBinding

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)

		setupAdapterViewFlipper()
	}

	private fun setupAdapterViewFlipper() {
		val adapterViewFlipper = AdapterViewFlipper(this, null)
		val layoutParams = LinearLayout.LayoutParams(
			ViewGroup.LayoutParams.MATCH_PARENT,
			ViewGroup.LayoutParams.MATCH_PARENT
		)
		adapterViewFlipper.layoutParams = layoutParams

		adapterViewFlipper.setInAnimation(applicationContext, R.animator.left_in)
		adapterViewFlipper.setOutAnimation(applicationContext, R.animator.right_out)

		adapterViewFlipper.flipInterval = 3200
		adapterViewFlipper.isAutoStart = true

		val nameList = arrayOf(
			"Guava",
			"JackFruit",
			"Mix Fruit",
			"Apple",
			"Pomegranate",
			"Strawberry",
			"Zespri Kiwi"
		)
		val imageList = intArrayOf(
			R.drawable.guava,
			R.drawable.jackfruit,
			R.drawable.mix_fruit,
			R.drawable.apple,
			R.drawable.pomegranate,
			R.drawable.strawberry,
			R.drawable.zespri_kiwi
		)

		val adapter = CustomAdapter(this, nameList, imageList)
		adapterViewFlipper.adapter = adapter

		binding.rootContainer.addView(adapterViewFlipper)
	}
}

Here, we have created adapterViewFlipper programmatically in kotlin file ( In MainActivity.kt file) in the application. Then, we have set layout params, in and out animations, flip intervals etc. in it. Then, we have created adapter and set it in AdapterViewFlipper. At last, we have added this adapterViewFlipper in linearLayout.

Finally, when you run the application, you will get output as shown above.

Tutorialwing Kotlin Dynamic AdapterViewFlipper Output Android AdapterViewFlipper Programmatically in Kotlin

Tutorialwing Kotlin Dynamic AdapterViewFlipper Output

Now, Let’s check how to use different attributes of AdapterViewFlipper to customize it dynamically –

Set Id of AdapterViewFlipper

Follow steps below to set id of AdapterViewFlipper programmatically –

  • Create ids.xml file in res/values folder. Then, add below code into it –
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <item type="id" name="adapterViewFlipper_ID" />
    </resources>
    
  • Now, we can set id of AdapterViewFlipper dynamically, in MainActivity.kt file, as –

    adapterViewFlipper.id = R.id.adapterViewFlipper_ID  // AdapterViewFlipper
    

    Here, we have set id of AdapterViewFlipper using property access syntax – adapterViewFlipper.id

Learn to Set ID of AdapterViewFlipper Using XML Attribute

Set Width and Height of AdapterViewFlipper

We use layoutParams to set width and height of any View programmatically. In this article, we have added AdapterViewFlipper in LinearLayout. So, we will define LayoutParams as below –

adapterViewFlipper.layoutParams = LinearLayout.LayoutParams(
	ViewGroup.LayoutParams.WRAP_CONTENT,
	ViewGroup.LayoutParams.WRAP_CONTENT
)

Here, we have set width and height as WRAP_CONTENT. Some of possible values for width and height are –

  • WRAP_CONTENT: Sets value of width or height depending on text inside it.
  • MATCH_PARENT: Sets value of width of height depending on width or height of parent layout . i.e. width or height of AdapterViewFlipper will be same as width or height of parent layout.
  • Fixed Value: Sets width or height as per value provided.

Learn to Set Width or Height of AdapterViewFlipper Using XML Attribute

Set Padding of AdapterViewFlipper

Follow steps below to set padding of AdapterViewFlipper Dynamically –

  • If there is no dimens.xml file, create dimens.xml file in res/values folder. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <dimen name="text_padding">16dp</dimen>
    </resources>
    
  • Now, we can set padding of AdapterViewFlipper dynamically, in MainActivity.kt file, as –
    val padding = resources.getDimension(R.dimen.text_padding).toInt()
    adapterViewFlipper.setPadding(padding, padding, padding, padding)
    

    Here, we have accessed dimension defined in dimens.xml using getDimension() method. Then, set padding of AdapterViewFlipper using setPadding() method.

Learn to Set Padding of AdapterViewFlipper Using XML Attribute

Set Margin of AdapterViewFlipper

Follow steps below to set margin of AdapterViewFlipper Dynamically –

  • If there is no dimens.xml file, create dimens.xml file in res/values folder. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <dimen name="text_margin">16dp</dimen>
    </resources>
    
  • Now, we can set margin of AdapterViewFlipper dynamically, in MainActivity.kt file, as –
    val margin = resources.getDimension(R.dimen.text_margin).toInt()
    val layoutParams = LinearLayout.LayoutParams(
    	ViewGroup.LayoutParams.WRAP_CONTENT,
    	ViewGroup.LayoutParams.WRAP_CONTENT
    )
    layoutParams.setMargins(margin, margin, margin, margin)
    adapterViewFlipper.layoutParams = layoutParams
    

    Here, we have accessed dimension defined in dimens.xml using getDimension() method. Then, we have defined layoutParams, set margin to layoutParams. After that, set layoutParams to AdapterViewFlipper.

Learn to Set Margin of AdapterViewFlipper Using XML Attribute

Set Background of AdapterViewFlipper

Follow steps below to set background of AdapterViewFlipper programmatically –

  • If there is no colors.xml file, create colors.xml file in res/values folder. Then, add below code in it –
    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <color name="purple_200">#FFBB86FC</color>
    </resources>
    
  • Now, we can set background of AdapterViewFlipper dynamically, in MainActivity.kt file, as –
    val color = ContextCompat.getColor(this, R.color.purple_200)
    adapterViewFlipper.setBackgroundColor(color)
    

    Here, we used setBackgroundColor() method to set background color in adapterViewFlipper.

Learn to Set Background of AdapterViewFlipper Using XML Attribute

Set Visibility of AdapterViewFlipper

We can set visibility of AdapterViewFlipper programmatically as –

adapterViewFlipper.visibility = View.VISIBLE

Here, we have set visibility of AdapterViewFlipper using adapterViewFlipper.visibility attribute. Visibility can be of three types – gone, visible and invisible.
Learn to Set Visibility of AdapterViewFlipper Using XML Attribute

That’s end of tutorial on AdapterViewFlipper Programmatically in Kotlin With Example.

Leave a Reply