In this article, we will learn about android ViewPager using Kotlin. We will go through various example that demonstrates how to use different attributes of ViewPager. We are going to learn about how to use android viewPager using kotlin with fragments in any android application. We will learn how to use FragmentPagerAdapter, what are it’s advantage, disadvantages etc.
In this article, we will get answer to questions like –
- What is ViewPager?
- Why should we consider ViewPager while designing ui for any app?
- What are possibilities using ViewPager while designing ui? etc.
Let’s have a quick demo of things we want to cover in this tutorial –
Output
Getting Started
We can define android ViewPager widget as below –
ViewPager is layout manager that allows the user to flip left and right through different pages.
We use PagerAdapter to create different views based on the data provided in the adapter. The created views is then provided to viewPager.
Now, how do we use ViewPager 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 ViewPager. 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 ViewPager 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.
Till Now, we have created an android application with name ViewPager. So, We will follow below steps to use viewPager. We will also access viewPager using kotlin file and do some operations on it.
- Modify values folder.
- Create Fragment pages to be used in the ViewPager.
- Create PagerAdapter For ViewPager.
- Define PagerTabStrip to show title with page.
- Define ViewPager in xml file.
- Access ViewPager Using Kotlin file and Perform Some operations.
Using ViewPager in Kotlin
Follow steps below to use ViewPager in newly created project –
- Open res/values/strings.xml file. Then, add below code into it.
<resources> <string name="app_name">ViewPager</string> <string name="no_image">No Image</string> <string name="tutorial_by">Tutorial By Tutorialwing.com</string> <string name="first_fragment">First Fragment</string> <string name="second_fragment">Second Fragment</string> <string name="third_fragment">Third Fragment</string> </resources>
-
Create Fragment Pages to be used in the viewPager
In this application, we will use three pages in viewPager. So, we need to create three fragment and it’s xml file. Below are the three fragments name that we are going to create now.
- (1) FirstFragment.kt and first_fragment.xml file
- (2) SecondFragment.kt and second_fragment.xml file
- (3) ThirdFragment.kt and third_fragment.xml file
Let’s create the view now.
-
Create First Fragment and it’s xml file
Create a new kotlin file, FirstFragment.kt, in src/main/java/com.tutorialwing.viewpager folder. Then, add below code into it.
package com.tutorialwing.viewpager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.tutorialwing.viewpager.databinding.FirstFragmentBinding class FirstFragment : Fragment() { private lateinit var binding: FirstFragmentBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FirstFragmentBinding.inflate(layoutInflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupData() } private fun setupData() { binding.txtMain.text = getString(R.string.first_fragment) binding.imgMain.setImageResource(R.mipmap.ic_launcher) } }
In this file, we have created view for first page.
Then, create a new xml file in res/layout folder with name first_fragment.xml. 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" android:background="@android:color/holo_blue_light"> <TextView android:id="@+id/headerLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:text="@string/tutorial_by" android:textColor="@android:color/white" android:textSize="18sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ImageView android:id="@+id/imgMain" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:contentDescription="@string/no_image" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/headerLabel" /> <TextView android:id="@+id/txtMain" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/white" android:textSize="17sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imgMain" /> </androidx.constraintlayout.widget.ConstraintLayout>
-
Create Second Fragment and it’s xml file
Create a new kotlin file, SecondFragment.kt, in src/main/java/com.tutorialwing.viewpager folder. Then, add below code into it.
package com.tutorialwing.viewpager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.tutorialwing.viewpager.databinding.SecondFragmentBinding class SecondFragment : Fragment() { private lateinit var binding: SecondFragmentBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = SecondFragmentBinding.inflate(layoutInflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupData() } private fun setupData() { binding.txtMain.text = getString(R.string.second_fragment) binding.imgMain.setImageResource(R.mipmap.ic_launcher) } }
In this file, we created view for second page.
Then, create a new xml file in res/layout folder with name second_fragment.xml. 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" android:background="@android:color/holo_red_dark"> <TextView android:id="@+id/headerLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:text="@string/tutorial_by" android:textColor="@android:color/white" android:textSize="18sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ImageView android:id="@+id/imgMain" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:contentDescription="@string/no_image" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/headerLabel" /> <TextView android:id="@+id/txtMain" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/white" android:textSize="17sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imgMain" /> </androidx.constraintlayout.widget.ConstraintLayout>
-
Create Third Fragment and it’s xml file
Create a new kotlin file, ThirdFragment.kt, in src/main/java/com.tutorialwing.viewpager folder. Then, add below code into it.
package com.tutorialwing.viewpager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.tutorialwing.viewpager.databinding.ThirdFragmentBinding class ThirdFragment : Fragment() { private lateinit var binding: ThirdFragmentBinding override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = ThirdFragmentBinding.inflate(layoutInflater) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupData() } private fun setupData() { binding.txtMain.text = getString(R.string.third_fragment) binding.imgMain.setImageResource(R.mipmap.ic_launcher) } }
In this file, we created view for third page.
Then, create a new xml file in res/layout folder with name third_fragment.xml. 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" android:background="@android:color/holo_orange_dark"> <TextView android:id="@+id/headerLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:text="@string/tutorial_by" android:textColor="@android:color/white" android:textSize="18sp" android:textStyle="bold" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <ImageView android:id="@+id/imgMain" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="20dp" android:contentDescription="@string/no_image" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/headerLabel" /> <TextView android:id="@+id/txtMain" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@android:color/white" android:textSize="17sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/imgMain" /> </androidx.constraintlayout.widget.ConstraintLayout>
-
Create And Use PagerAdapter For Android ViewPager
Create a new kotlin file, ViewPagerAdapter.kt, in src/main/java/com.tutorialwing.viewpager folder. Then, add below code into it.
package com.tutorialwing.viewpager import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter class ViewPagerAdapter(fm: FragmentManager): FragmentPagerAdapter(fm) { private val COUNT = 3 override fun getItem(position: Int): Fragment { return when (position) { 0 -> FirstFragment() 1 -> SecondFragment() 2 -> ThirdFragment() else -> FirstFragment() } } override fun getCount(): Int { return COUNT } override fun getPageTitle(position: Int): CharSequence? { return "Tab " + (position + 1) } }
Adapter class is used to create views for viewPager based on the data provided to it. Here, we have subclassed FragmentPagerAdapter to create view. Use this class only when you are creating more static fragments i.e. when data doesn’t change frequently. If you are implementing fragments in which data changes frequently, you need to subclass from FragmentStatePagerAdapter.
-
Define PagerTitleStrip to Show title With Each Page
<androidx.viewpager.widget.PagerTitleStrip android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="top" android:background="@color/purple_500" android:padding="13dp" />
PagerTitleStrip is used to show title for each page in the viewPager. Method getPageTitle(position: Int) in ViewPagerAdapter class is responsible to provide title in PagerTitleStrip. We use this PagerTitleStrip in viewPager. You can see how to do it in activity_main.xml file.
-
Use Android ViewPager in xml file
Open res/layout/activity_main.xml file. Then, add below code in it –
<?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout 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"> <androidx.viewpager.widget.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <androidx.viewpager.widget.PagerTitleStrip android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="top" android:background="@color/purple_500" android:padding="13dp" /> </androidx.viewpager.widget.ViewPager> </androidx.coordinatorlayout.widget.CoordinatorLayout>
In activity_main.xml file, we have defined viewPager class. Note that PagerTitleStrip widget is placed inside viewPager to show title for each page in the viewPager.
-
Access Android ViewPager Using Kotlin file
We can also access it in Kotlin File, MainActivity.kt, as below –
package com.tutorialwing.viewpager import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.tutorialwing.viewpager.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) setupViewPager() } private fun setupViewPager() { val viewPager = binding.viewPager viewPager.adapter = ViewPagerAdapter(supportFragmentManager) } }
Here, we have accessed the viewPager using kotlin file (i.e. in MainActivity.kt file). Then, we have created an adapter, to create views, and set it to viewPager.
Now, run the application. We will get output as below –
Different Attributes of ViewPager in XML
Now, we will see how to use different attributes of Android ViewPager using Kotlin to customise it –
Set Id of ViewPager
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 ViewPager using android:id attribute like below –
<ViewPager android:id="@+id/viewPager_ID" />
Here, we have set id of ViewPager as viewPager_ID using android:id=”” attribute. So, if we need to reference this ViewPager, we need to use this id – viewPager_ID.
Learn to Set ID of ViewPager Dynamically
Set Width of ViewPager
We use android:layout_width=”” attribute to set width of ViewPager.
We can do it as below –
<ViewPager android:id="@+id/viewPager_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 ViewPager Dynamically
Set Height of ViewPager
We use android:layout_height=”” attribute to set height of ViewPager.
We can do it as below –
<ViewPager android:id="@+id/viewPager_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 ViewPager Dynamically
Set Padding of ViewPager
We use android:padding=”” attribute to set padding of ViewPager.
We can do it as below –
<ViewPager android:id="@+id/viewPager_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" />
Here, we have set padding of 10dp in ViewPager using android:padding=”” attribute.
Learn to Set Padding of ViewPager Dynamically
Set Margin of ViewPager
We use android:layout_margin=”” attribute to set margin of ViewPager.
We can do it as below –
<ViewPager android:id="@+id/viewPager_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="10dp" />
Here, we have set margin of 10dp in ViewPager using android:layout_margin=”” attribute.
Learn to Set Margin of ViewPager Dynamically
Set Background of ViewPager
We use android:background=”” attribute to set background of ViewPager.
We can do it as below –
<ViewPager android:id="@+id/viewPager_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#ff0000" />
Here, we have set background of color #ff0000 in ViewPager using android:background=”” attribute.
Learn to Set Background of ViewPager Dynamically
Set Visibility of ViewPager
We use android:visibility=”” attribute to set visibility of ViewPager.
We can do it as below –
<ViewPager android:id="@+id/viewPager_ID" android:layout_width="wrap_content" android:layout_height="wrap_content" android:visibility="gone" />
Here, we have set visibility of ViewPager using android:visiblity=”” attribute. Visibility can be of three types – gone, visible and invisible
Learn to Set Visibility of ViewPager Dynamically
Till now, we have see how to use android ViewPager using Kotlin. We have also gone through different attributes of ViewPager to perform certain task. Let’s have a look at list of such attributes and it’s related task.
Different Attributes of Android ViewPager Widget
Below are the various attributes that are used to customise android ViewPager Widget. However, you can check the complete list of attributes of ViewPager 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 viewPager inherited from viewGroup are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:animateLayoutChanges | Defines whether to run layout transition when there is any change in layout |
2 | android:animationCache | Defines whether to create drawing cache for children by layout animation |
3 | android:clipToPadding | Defines 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 | Defines the layout animation to be used when the viewGroup is laid out for the first time |
5 | android:layoutMode | Specifies the layout mode of the viewGroup |
Some of the popular attributes of android viewPager inherited from View are –
Sr. | XML Attributes | Description |
---|---|---|
1 | android:alpha | Defines alpha to the view |
2 | android:background | Defines drawable to the background |
3 | android:backgroundTint | Defines tint to apply to the background |
4 | android:clickable | Defines whether the view is clickable or not |
5 | android:elevation | Defines elevation of the view |
6 | android:focusable | Defines whether this view can take focus or not |
7 | android:id | Defines id of the view |
8 | android:visibility | Defines the visibility(VISIBLE, INVISIBLE, GONE) of the view |
We have seen different attributes of ViewPager and how to use it. If you wish to visit post to learn more about it
Thus, we have seen what is ViewPager, how can we use android ViewPager using Kotlin ? etc. We also went through different attributes of android ViewPager.
You must be logged in to post a comment.