Onboarding Screens with ViewPager Android

Published March 26, 2021

When user first time visit your android application to give more info on the first time, to give more info about your application we will show OnBoarding screens on the first time. Onboarding UI is the most important place to attract the users on the first visit. In this post we will create Android OnBoarding UI with ViewPager. This OnBoarding UI library contains viewpager with fragment. This OnBoarding screens UI involved the Android Navigation Component, Android ViewPager2 and Fragment.

 

Let's get started

Step 1: Create Android application in Android studio

Step 2: Remove default activities and layout and create a new Activity. Here i have created activity with Name StartActivity.kt

Now we are going to add Navigation component to the layout file. To Use Navigation Component UI we need to add below dependencies in build.gradle file

implementation 'androidx.navigation:navigation-fragment-ktx:2.3.4'
implementation 'androidx.navigation:navigation-ui-ktx:2.3.4'

 

Now add NavHost to our xml file. Now our xaml file will be looks like below

<?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:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >



  <androidx.fragment.app.FragmentContainerView
      android:id="@+id/nav_host_fragment"
      android:name="androidx.navigation.fragment.NavHostFragment"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:defaultNavHost="true"

      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintLeft_toLeftOf="parent"
      app:layout_constraintRight_toRightOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      app:navGraph="@navigation/mobile_navigation" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

In the above we added a fragment as child to ConstraintLayout. To this fragment widget we have added the class "NavHostFragment"

NavHostFragment provides an area within your layout for self-contained navigation

We also added app:navGraph with the Navigation layout which will used to maintian out Fragment navigation within the layout.

The mobile_navigation will be likw below

<?xml version="1.0" encoding="utf-8"?>
<navigation 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:id="@+id/mobile_navigation"
    app:startDestination="@id/splashFragment">

    <fragment
        android:id="@+id/navigation_home"
        android:name="com.android.videos.myapplication.authentication.ui.home.HomeFragment"
        android:label="@string/title_home"
        tools:layout="@layout/fragment_home" />

    <fragment
        android:id="@+id/splashFragment"
        android:name="com.android.videos.myapplication.authentication.ui.SplashFragment"
        android:label="fragment_splash"
        app:launchSingleTop="true"
        tools:layout="@layout/fragment_splash"

        >


        <action
            android:id="@+id/action_splashFragment_to_navigation_home"
            app:destination="@id/navigation_home"
            app:popUpTo="@id/splashFragment"
            app:popUpToInclusive="true" />

        <action
            android:id="@+id/action_splashFragment_to_viewPagerFragment"
            app:destination="@id/viewPagerFragment"

            app:popUpTo="@id/splashFragment"
            app:popUpToInclusive="true" />
    </fragment>

    <fragment
        android:id="@+id/viewPagerFragment"
        android:name="com.android.videos.myapplication.authentication.ui.onboarding.ViewPagerFragment"
        android:label="fragment_view_pager"
        tools:layout="@layout/fragment_view_pager" >

        <action
            android:id="@+id/action_viewPagerFragment_to_navigation_home"
            app:destination="@id/navigation_home"
            app:popUpTo="@id/viewPagerFragment"
            app:popUpToInclusive="true" />
    </fragment>
</navigation>

 

This navigation layout contains 3 fragments SplashFragment,HomeFragment and ViewPagerFragment. Create these 3 fragments.

 

Step 3: Now its time to create our Onboarding Screens.

We are showing Our Onboarding screens with 3 fragments, each fragment contains a imageview,textview. Where we will show these 3 fragments, yes we will show these 3 fragments inside viewpager fragment which will have the ViewPager2 widget.

Our ViewPager Fragment xml will be likw this

<?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:id="@+id/frameLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".authentication.ui.onboarding.ViewPagerFragment" >

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

 

To add fragments to viewpager we need to create an adapter ViewPagerAdapter.kt will be like below

class ViewPagerAdapter(list:ArrayList<Fragment>,fm:FragmentManager,lifecycle: Lifecycle):FragmentStateAdapter(fm,lifecycle) {
    val fragmentList=list;
    override fun getItemCount(): Int {

        return fragmentList.size
    }

    override fun createFragment(position: Int): Fragment {
        return fragmentList[position]
    }

}

 

Update our ViewPagerFragment code

package com.android.videos.myapplication.authentication.ui.onboarding

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager2.widget.ViewPager2
import com.android.videos.myapplication.R
import com.android.videos.myapplication.authentication.ui.onboarding.screens.FirstFragment
import com.android.videos.myapplication.authentication.ui.onboarding.screens.SecondFragment
import com.android.videos.myapplication.authentication.ui.onboarding.screens.ThirdFragment

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [ViewPagerFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class ViewPagerFragment : Fragment() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
    }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val fragmentList= arrayListOf<Fragment>(FirstFragment(),SecondFragment(),ThirdFragment())
        val viewpager=getView()?.findViewById<ViewPager2>(R.id.viewpager)
        viewpager?.adapter=ViewPagerAdapter(fragmentList,childFragmentManager,lifecycle)

    }


}

 

Step 4: We are ready with our SplashScreen,OnBoarding Screen and How Screen. Now how to navigate these screens? To Navigate these screens from each of which we will use NavigationController.

So when we are on the Splashscreen then navigate to OnBoarding Screens/Homescreen we will use the below code

findNavController().navigate(R.id.action_splashFragment_to_viewPagerFragment)

 

Here findNavController() will give the current Navigation Controller and to navigate we will use the navigate() methos. To thiis method we will pass the action id. this action id will be created inside our navigation layout file mobile_navigation.

To save the state of OnBoarding Screens we will store the boolean value inside SharedPreferences()

When we will finish the onboarding screens we will store the value as true inside sharedPreferences.

fun addPref()
{
    val shpf=requireContext().getSharedPreferences("OnBoarding", Context.MODE_PRIVATE)
    shpf.edit().apply {  putBoolean("finished",true)}.apply()
}

.

our SplashScreen will be look like this

package com.android.videos.myapplication.authentication.ui

import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.OnBackPressedCallback
import androidx.navigation.Navigation
import androidx.navigation.fragment.findNavController
import com.android.videos.myapplication.R

class SplashFragment : Fragment() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {

        }
        val onBackPressedCallback = object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {

                requireActivity().finish()
            }
        }
        requireActivity().getOnBackPressedDispatcher().addCallback(this, onBackPressedCallback)

    }

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

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        Handler(Looper.getMainLooper()).postDelayed(Runnable {

            if (getOnBoardStatus())
                findNavController().navigate(R.id.action_splashFragment_to_navigation_home)
            else
                findNavController().navigate(R.id.action_splashFragment_to_viewPagerFragment)

        }, 3000)
    }


    fun getOnBoardStatus(): Boolean {

        return requireActivity().getSharedPreferences("OnBoarding", Context.MODE_PRIVATE)
            .getBoolean("finished", false)
    }
}

 

Android Onboarding Screen UI Library

 

Download Source code

 

Related Topics

Android NavigationView, NavigationDrawer Layout

GooglePLay InApp Purchase Integration

Android JobScheduler

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1985 Views