TabLayout with Sliding and Clickable Tabs Using View Pager and Fragment

Hi guy, In this tutorial we are going to learn how to work with TabLayout with Sliding and Clickable Tabs Using View Pager and Fragment. TabLayout aid in displaying more views in a single screen. viewPager allow user to view different view by flipping screen left to right or right to left. pagerAdapter is used to generate view shown by viewPager. Tabs are added to TabLayout which when clicked also change the view depending on the tab that was tapped. A good example of TabLayout is WhatsApp tabs where you can flip multiple view in one screen.

TabLayout with Sliding and Clickable Tabs Using View Pager and Fragment

In this tutorial, we will develop an application shown in the image above, The application will have 3 tabs which when tapped or scrolled will display different texts in the single screen.

  • Open tab2 and copy paste the code below.
  • Open tab3, copy and paste the code below.
  • Adding Frament class to inflate our tabs

  • Create 3 java class that will inflate our tabs.
  • right click on your package class => New => Java class and name it Tab1 .
  • Repeat the same for the next two class, Name the Second class Tab2 and Third class Tab3.
  • Adding Fragment TabLayout

  • Each class will extend Fragment and will inflate the tab file in the onCreateView method.
  • In your Tab1 class copy and paste the code below in it.
  • Open Tab2, copy and Paste the code below.
  • Open Tab3, copy and paste the code below.
  • Removing ActionBar from Our Theme

  • Since we are working with ToolBar hence remove ActionBar.
  • Open styles.xml located under values.
  • Modify your theme by removing Action Bar.
  • Adding ToolBar, TabLayout and viewPager

  • ToolBar replaces ActionBar.
  • TabLayout is for adding tabs.
  • viewPager is a view that allow us to view different view by just flipping left or right.
  • Open your activity_main.xml file.
  • Creating pagerAdapter

  • pagerAdapter generate the view shown in viewPager.
  • Create a new java class and call it pagerAdapter.
  • Adding tabs to TabLayout, setting viewPager adapter and listening tab selected.

  • MainActivity class implement TabLayout.TabSelectedListener.
  • Adding tabs to Tablayout in MainActivity.
  • Adding viewPager in MainActivity.
  • listening tab selected.
  • The final code for MainActivity class will be as shown below.

  • That is it, Run your Application and you will see the output similar to one below.
  • You can change view by tapping tabs
  • TabLayout with Sliding and Clickable Tabs Using View Pager and Fragment

  • You can also change view by sliding view
  • TabLayout with Sliding and Clickable Tabs Using View Pager and Fragment

  • To download the source code click the link below
  • download source code
  • If you need help or have any question let me know by commenting below.