viewpager

ViewPager using Fragment in Android with Example

Today we are implementing a ViewPager using Fragment. ViewPager on Android allows users to flip through from left to right.

In ViewPager App, we implemented a ViewPager that can navigate in two Fragments with different text. The Android ViewPager widget is in the support library and allows users to swipe left or right to view a completely new screen.

Viewpager implementation steps:

  • Including the ViewPager widget in the XML layout (typically the main layout).
  • Extending the FragmentPagerAdapter classes to create an Adapter.
  • An adapter populates the Viewpager’s pages. PagerAdapter is the base class from which FragmentPagerAdapter and FragmentStatePagerAdapter extend. 

Difference between FragmentPagerAdapter / FragmentStatePagerAdapter

  • FragmentStatePagerAdapter: Only keeps the current fragment displayed on the screen in memory. This saves memory and should be used in applications that use dynamic fragments. (In this case, the number of fragments is not fixed.)
  • FragmentPagerAdapter: Use this adapter when the number of fragments is fixed. An application with three tabs that will not change during the application’s runtime. The FragmentPagerAdapter will be used in this tutorial.

Preview: ViewPager Using Fragments

<–ViewPager Example

File: MainActivity.kt

package com.sagar.fragmentwithtablayoutviewpager

import android.os.Bundle
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout

class MainActivity : AppCompatActivity() {

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

        var tab_viewpager = findViewById<ViewPager>(R.id.tab_viewpager)
        var tab_tablayout = findViewById<TabLayout>(R.id.tab_tablayout)


        setupViewPager(tab_viewpager)


        tab_tablayout.setupWithViewPager(tab_viewpager)
    }


    private fun setupViewPager(viewpager: ViewPager) {
        var adapter: ViewPagerAdapter = ViewPagerAdapter(supportFragmentManager)

        adapter.addFragment(login_fragment(), "Login")
        adapter.addFragment(sign_up_fragment(), "Signup")

        viewpager.setAdapter(adapter)
    }


    class ViewPagerAdapter : FragmentPagerAdapter {

        private  var fragmentList1: ArrayList<Fragment> = ArrayList()
        private  var fragmentTitleList1: ArrayList<String> = ArrayList()

         constructor(supportFragmentManager: FragmentManager)
                : super(supportFragmentManager)

        override fun getItem(position: Int): Fragment {
            return fragmentList1.get(position)
        }

        @Nullable
        override fun getPageTitle(position: Int): CharSequence {
            return fragmentTitleList1.get(position)
        }

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

        fun addFragment(fragment: Fragment, title: String) {
            fragmentList1.add(fragment)
            fragmentTitleList1.add(title)
        }
    }
}

File: activity_main.xml

<?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">


    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#0F9D58"
        android:theme="@style/AppTheme.AppBarOverlay">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tab_tablayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabIndicatorColor="#FFF"
            app:tabIndicatorHeight="3dp"
            app:tabMode="fixed" />
    </com.google.android.material.appbar.AppBarLayout>


    <androidx.viewpager.widget.ViewPager
        android:id="@+id/tab_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="5dp"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />


</androidx.coordinatorlayout.widget.CoordinatorLayout>



File: Login_fragment.kt

package com.sagar.fragmentwithtablayoutviewpager

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class login_fragment : Fragment() {


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_login_fragment, container, false)
    }

    }

File: fragment_login_fragment.xml

<?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:gravity="center">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Login Fragment"
        android:textColor="#880E4F"
        android:textSize="25sp"
        android:textStyle="bold" />

</LinearLayout>

File: sign_up_fragment.kt

package com.sagar.fragmentwithtablayoutviewpager

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

class sign_up_fragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_sign_up_fragment, container, false)
    }


    }

File:fragment_sign_up_fragment.xml

<?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:gravity="center">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="Signup Fragment"
        android:textColor="#880E4F"
        android:textSize="25sp"
        android:textStyle="bold" />

</LinearLayout>

File: themes.xml

<resources xmlns:tools="http://schemas.android.com/tools">
    <!-- Base application theme. -->
    <style name="Theme.Fragmentwithtablayoutviewpager" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
        <!-- Primary brand color. -->
        <item name="colorPrimary">@color/purple_500</item>
        <item name="colorPrimaryVariant">@color/purple_700</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/black</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
        <!-- Customize your theme here. -->
    </style>
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay"

        parent="ThemeOverlay.AppCompat.Dark.ActionBar"
        />

    <style name="AppTheme.PopupOverlay"
        parent="ThemeOverlay.AppCompat.Light" />

</resources>
  • We hope that this guide will assist you in quickly creating a simple Viewpager using fragment . If you have any problems, please post them in the comments section and we will gladly assist you.

This Post Has 4 Comments

Leave a Reply