Android AppBarLayout With ViewPager and Toolbar

In this article, we will use android appBarLayout With ViewPager and Toolbar in Kotlin. We will design a ui that can be scrolled up and down to show or hide toolBar.

Let’s have a quick demo of things we want to cover in this tutorial –

Output

Tutorialwing Kotlin Android AppBarLayout With TabLayout, ViewPager and Toolbar in Kotlin With Example

Getting Started

We have already seen how to covered basics of AppBarLayout, ViewPager or Toolbar. In this article, we are going to create an application combining all of them. We are going to create a tabular view with ViewPager in toolBar that can be scrolled up and down.

Now, how do we use these widgets in android application ? Follow steps to do it –

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 AppBarLayoutWithViewPager. 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 Views 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.

Using AppBarLayout, TabLayout and ViewPager in Kotlin

Follow steps below –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">AppBarLayoutWithViewPager</string>
        <string name="video_playlist">Video Playlist</string>
        <string name="audio_playlist">Audio Playlist</string>
        <string name="homepage">Homepage</string>
        <string name="gallery">Gallery</string>
    </resources>
    
  • Here, we are going to use android appBarLayout with viewPager and Toolbar. Since are going to display three fragments with ViewPager, we need to them first. So, follow steps below to create fragments –
    1. Create First Fragment

      Create new xml file, gallery_fragment.xml, in res/layout folder. Then, add below code in 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/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintTop_toTopOf="parent" />
      
      </androidx.constraintlayout.widget.ConstraintLayout>
      

      Now, create new Kotlin file, GalleryFragment.kt, in res/layout folder. Then, add below code in it –

      package com.tutorialwing.appbarlayoutwithviewpager
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.appbarlayoutwithviewpager.databinding.GalleryFragmentBinding
      
      class GalleryFragment : Fragment() {
      
      	private lateinit var binding: GalleryFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = GalleryFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.gallery)
      	}
      }
      
    2. Create Second Fragment

      Create new xml file, audio_fragment.xml, in res/layout folder. Then, add below code in 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_light">
      
          <TextView
              android:id="@+id/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintTop_toTopOf="parent" />
      
      </androidx.constraintlayout.widget.ConstraintLayout>
      

      Now, create new Kotlin file, AudioFragment.kt, in com.tutorialwing.appbarlayoutwithviewpager package. Then, add below code in it –

      package com.tutorialwing.appbarlayoutwithviewpager
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.appbarlayoutwithviewpager.databinding.AudioFragmentBinding
      
      class AudioFragment : Fragment() {
      
      	private lateinit var binding: AudioFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = AudioFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.audio_playlist)
      	}
      }
      

      Here, we have accessed xml file then set text to textView in setupData() method called from onCreateMethod() method.

    3. Create Third Fragment

      Create new xml file, video_fragment.xml, in res/layout folder. Then, add below code in 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_light">
      
          <TextView
              android:id="@+id/label"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              app:layout_constraintBottom_toBottomOf="parent"
              app:layout_constraintEnd_toEndOf="parent"
              app:layout_constraintStart_toStartOf="parent"
              app:layout_constraintTop_toTopOf="parent" />
      
      </androidx.constraintlayout.widget.ConstraintLayout>
      

      Then, create new Kotlin file, VideoFragment.kt, in com.tutorialwing.appbarlayoutwithviewpager package. Then, add below code in it –

      package com.tutorialwing.appbarlayoutwithviewpager
      
      import android.os.Bundle
      import android.view.LayoutInflater
      import android.view.View
      import android.view.ViewGroup
      import androidx.fragment.app.Fragment
      import com.tutorialwing.appbarlayoutwithviewpager.databinding.VideoFragmentBinding
      
      class VideoFragment : Fragment() {
      
      	private lateinit var binding: VideoFragmentBinding
      
      	override fun onCreateView(
      		inflater: LayoutInflater,
      		container: ViewGroup?,
      		savedInstanceState: Bundle?
      	): View {
      		binding = VideoFragmentBinding.inflate(layoutInflater)
      		return binding.root
      	}
      
      	override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
      		super.onViewCreated(view, savedInstanceState)
      
      		setupData()
      	}
      
      	private fun setupData() {
      		binding.label.text = getString(R.string.video_playlist)
      	}
      }
      
  • Create Adapter for ViewPager

    Till now, we have created fragments needed for viewPager. Now, we will create adapter that provides data to viewPager. So, create new file, ViewPagerAdapter.kt, in com.tutorialwing.appbarlayoutwithviewpager package. Then, add below code in it –

    package com.tutorialwing.appbarlayoutwithviewpager
    
    import androidx.fragment.app.Fragment
    import androidx.fragment.app.FragmentManager
    import androidx.fragment.app.FragmentPagerAdapter
    
    class ViewPagerAdapter(fm: FragmentManager, var tabCount: Int) : FragmentPagerAdapter(fm) {
    
    	override fun getItem(position: Int): Fragment {
    		return when (position) {
    			0 -> GalleryFragment()
    			1 -> AudioFragment()
    			2 -> VideoFragment()
    			else -> GalleryFragment()
    		}
    	}
    
    	override fun getCount(): Int {
    		return tabCount
    	}
    
    	override fun getPageTitle(position: Int): CharSequence {
    		return "Tab " + (position + 1)
    	}
    }
    

    Here, we are return fragments based on selected tab.

    1. If first tab is selected, we are showing GalleryFragment.
    2. If second tab is selected, we are showing AudioFragment.
    3. If third tab is selected, we are showing VideoFragment.
  • Now, 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">
    
        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appBarLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    
            <androidx.appcompat.widget.Toolbar
                android:id="@+id/toolBar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="?attr/colorPrimary"
                android:minHeight="?attr/actionBarSize"
                android:theme="?attr/actionBarTheme"
                app:layout_anchor="@+id/appBarLayout"
                app:layout_anchorGravity="bottom|center"
                app:layout_scrollFlags="scroll|enterAlways" />
    
            <com.google.android.material.tabs.TabLayout
                android:id="@+id/tabLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                app:tabIndicatorHeight="3dp"
                app:tabMode="fixed" />
    
        </com.google.android.material.appbar.AppBarLayout>
    
        <androidx.core.widget.NestedScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:fillViewport="true"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">
    
            <androidx.viewpager.widget.ViewPager
                android:id="@+id/viewPager"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
    
        </androidx.core.widget.NestedScrollView>
    
    </androidx.coordinatorlayout.widget.CoordinatorLayout>
    

    Here, we have AppBarLayout. Inside it, we have used toolbar and tabLayout. Then, we have used NestedScrollView. Inside it, there is ViewPager. When screen is scrolled up, TabLayout and NestedScrollView and it’s content is visible. ToolBar is hidden when we scroll up. it becomes visible when ui is scrolled down.

  • Now, we do some setup in Kotlin file. So, open MainActivity.kt and add below code in it –

    package com.tutorialwing.appbarlayoutwithviewpager
    
    import android.os.Bundle
    import androidx.appcompat.app.AppCompatActivity
    import com.tutorialwing.appbarlayoutwithviewpager.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setSupportActionBar(binding.toolBar)
    
    		setupTabLayout()
    		setupViewPager()
    
    		binding.tabLayout.setupWithViewPager(binding.viewPager)
    	}
    
    	private fun setupViewPager() {
    		binding.viewPager.apply {
    			adapter = ViewPagerAdapter(supportFragmentManager, binding.tabLayout.tabCount)
    		}
    	}
    
    	private fun setupTabLayout() {
    		binding.tabLayout.apply {
    			addTab(this.newTab().setText(getString(R.string.gallery)))
    			addTab(this.newTab().setText(getString(R.string.audio_playlist)))
    			addTab(this.newTab().setText(getString(R.string.video_playlist)))
    		}
    	}
    }
    

Now, run the application. We will get output as below –
Tutorialwing Kotlin Android AppBarLayout With ViewPager in Kotlin

That’s end of tutorial on android appBarLayout With ViewPager and Toolbar.

Leave a Reply