Android ViewPager Using Kotlin With Fragment

Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners. Also, if you are interested in content writing, you can mail us at tutorialwing@gmail.com.

Hello Reader! In this post, 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.

Output

Tutorialwing Kotlin ViewPager Output Android ViewPager Using Kotlin With Example

Tutorialwing Kotlin ViewPager Output

Getting Started

Android ViewPager can be defined as below –

ViewPager is layout manager that allows the user to flip left and right through different pages. It is found in support library.

We use PagerAdapter to create different views based on the data provided in the adapter. The created views is then provided to viewPager.




Example of Android ViewPager Using Kotlin With Fragments

At first, we will create android application. Then, we will use viewPager in this application.

1. Creating New Project

Follow steps below to create new project. Please ignore the steps if you have already created a new application.

Step Description
1. Open Android Studio.
2. Go to File => New => New Project. Write application name as ViewPager. Then, check Include Kotlin Support and click next button.
3. Select minimum SDK you need. However, we have selected 17 as minimum SDK. Then, click next button
4. Then, select Empty Activity => click next => click finish.
5. You will get a newly created project successfully if you have followed steps properly.

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.

A. Modify values folder.
B. Create Fragment pages to be used in the ViewPager.
C. Create PagerAdapter For ViewPager.
D. Defined PagerTabStrip to show title with page.
E. Define ViewPager in xml file.
F. Access ViewPager Using Kotlin file and Perform Some operations.

2.1 Modify Values folder

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>

Don’t worry, these string constants will be used later in this tutorial.

2.2 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.java and first_fragment.xml file
(2) SecondFragment.java and second_fragment.xml file
(3) ThirdFragment.java and third_fragment.xml file

Let’s create the view now.

2.2.1 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.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView

class FirstFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val view = inflater.inflate(R.layout.first_fragment, container, false)
        val textView = view.findViewById<TextView>(R.id.txtMain)
        textView.setText(R.string.first_fragment)

        val imageView = view.findViewById<ImageView>(R.id.imgMain)
        imageView.setImageResource(R.mipmap.ic_launcher)

        return view
    }
}

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"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	android:background="@android:color/holo_blue_light"
	android:gravity="center"
	android:orientation="vertical">

	<TextView
		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"/>

	<ImageView
		android:id="@+id/imgMain"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_marginBottom="20dp"
		android:contentDescription="@string/no_image"/>

	<TextView
		android:id="@+id/txtMain"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:textColor="@android:color/white"
		android:textSize="17sp"/>

</LinearLayout>

2.2.2 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.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView

class SecondFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val view = inflater.inflate(R.layout.second_fragment, container, false)
        val textView = view.findViewById<TextView>(R.id.txtMain)
        textView.setText(R.string.second_fragment)

        val imageView = view.findViewById<ImageView>(R.id.imgMain)
        imageView.setImageResource(R.mipmap.ic_launcher)

        return view
    }
}

In this file, we created view for second page.

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

	<TextView
		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"/>

	<ImageView
		android:id="@+id/imgMain"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_marginBottom="20dp"
		android:contentDescription="@string/no_image"/>

	<TextView
		android:id="@+id/txtMain"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:textColor="@android:color/white"
		android:textSize="17sp"/>

</LinearLayout>

2.2.3 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.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView

class ThirdFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

        val view = inflater.inflate(R.layout.third_fragment, container, false)
        val textView = view.findViewById<TextView>(R.id.txtMain)
        textView.setText(R.string.third_fragment)

        val imageView = view.findViewById<ImageView>(R.id.imgMain)
        imageView.setImageResource(R.mipmap.ic_launcher)

        return view
    }
}

In this file, we created view for third page.

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

	<TextView
		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"/>

	<ImageView
		android:id="@+id/imgMain"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_marginBottom="20dp"
		android:contentDescription="@string/no_image"/>

	<TextView
		android:id="@+id/txtMain"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:textColor="@android:color/white"
		android:textSize="17sp"/>

</LinearLayout>

2.3 Create And Use PagerAdapter For Android ViewPager

Create a new kotlin file, ViewPageAdapter.kt, in src/main/java/com.tutorialwing.viewpager folder. Then, add below code into it.

package com.tutorialwing.viewpager

import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter

class ViewPagerAdapter internal constructor(fm: FragmentManager) : FragmentPagerAdapter(fm) {

    private val COUNT = 3

    override fun getItem(position: Int): Fragment? {
        var fragment: Fragment? = null
        when (position) {
            0 -> fragment = FirstFragment()
            1 -> fragment = SecondFragment()
            2 -> fragment = ThirdFragment()
        }

        return fragment
    }

    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.

2.4 Define PagerTabStrip to Show title With Each Page

<android.support.v4.view.PagerTabStrip
	android:id="@+id/pager_header"
	android:layout_width="match_parent"
	android:layout_height="wrap_content"
	android:layout_gravity="top"
	android:background="@color/colorPrimary"
	android:padding="10dp"/>

PagerTabStrip is used to show title for each page in the viewPager. Method getPageTitle(position: Int) in ViewPagerAdapter class is responsible to provide title in PagerTabStrip. We use this PagerTabStrip in viewPager. You can see how to do it in activity_main.xml file.

3. Use Android ViewPager in xml file

Open res/layout/activity_main.xml file. Then, add below code into it.

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

	<android.support.v4.view.ViewPager
		android:id="@+id/viewPager"
		android:layout_width="match_parent"
		android:layout_height="match_parent">

		<android.support.v4.view.PagerTabStrip
			android:id="@+id/pager_header"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:layout_gravity="top"
			android:background="@color/colorPrimary"
			android:padding="13dp"/>

	</android.support.v4.view.ViewPager>

</LinearLayout>

In activity_main.xml file, we have defined viewPager class. Note that PagerTabStrip widget is placed inside viewPager to show title for each page in the viewPager.

4. Access Android ViewPager Using Kotlin file

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

package com.tutorialwing.viewpager

import android.os.Bundle
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val viewPager = findViewById<ViewPager>(R.id.viewPager)
        if (viewPager != null) {
            val adapter = ViewPagerAdapter(supportFragmentManager)
            viewPager.adapter = adapter
        }
    }
}

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.

Since AndroidManifest.xml file is very important in any android application, we are also going to see the content inside this file.

AndroidManifest.xml

Code inside src/main/AndroidManifest.xml file is as below –

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.tutorialwing.viewpager"
		  xmlns:android="http://schemas.android.com/apk/res/android">

	<application
		android:allowBackup="true"
		android:icon="@mipmap/ic_launcher"
		android:label="@string/app_name"
		android:roundIcon="@mipmap/ic_launcher_round"
		android:supportsRtl="true"
		android:theme="@style/AppTheme">
		<activity android:name=".MainActivity">
			<intent-filter>
				<action android:name="android.intent.action.MAIN"/>

				<category android:name="android.intent.category.LAUNCHER"/>
			</intent-filter>
		</activity>
	</application>

</manifest>

When we run the program, we will get output as shown above.

That’s end of tutorial on Android ViewPager.

Support Us

If you like Tutorialwing and would like to contribute, you can email an article on any educational topic at tutorialwing@gmail.com. We would love to publish your article. See your article on Tutorialwing and help others with your knowledge. Follow Facebook, LinkedIn, Google+, Twitter, Youtube for latest updates.
Greetings!
We have recently published 100+ articles on android tutorials with kotlin and java. If you need, you may visit Android Tutorial for beginners page. You can also check Kotlin Tutorial for beginners