This demo was created to help everyone learn how to make swipeable interface in android studio. The code is commented and explained.
- download the source code
- unzip it in any folder you want
- open Android Studio
- navigate to File > Open > Your folder
- run on your device
When following this tutorial please refer to source code in this repository.
- Create your main class (
MainActivity.java
) - Create main layout which will include tab menu and ViewPager2 (
activity_main.xml
) - Create class which extends FragmentStateAdapter for managing fragments (
ViewPagerAdapter.java
)- This class will extend
FragmentStateAdapter
- We will overwrite methods
createFragment
andgetItemCount
- Those methods need to be overwritten so the
ViewPager2
gets fragments from ourList
- Those methods need to be overwritten so the
- This class will extend
- Create layouts for fragments (
first_fragment.xml
,second_fragment.xml
,third_fragment.xml
) - Create classes for our fragments (
FirstFragment.java
,SecondFragment.java
,ThirdFragment.java
, ...)- Each
Fragment
will be our view and item in tab menu - How to handle buttons is described in
SecondFragment.java
- Each
- Now we'll make some changes in our main class in order to make this app work (refer to
MainActivity.java
)- Set
activity_main.xml
as its layout - Initiate
ViewPager
- add element which will be displaying our fragments (in our case it will be element with idviewPager
) - Create
List
ofMaps
where we will store our fragments- Maps will help us get to the correct fragment by using its name
- Create
Maps
ofFragments
(we will create methodsetTablTitleAndFragment
to help us do that) and add them to theList
- Create
ViewPagerAdapter
instance and pass him our main class (activity
) andList
with ourFragments
- We also added
TabLayout
in ouractivity_main.xml
so we will tell our main class to use it- this will populate the menu
- Finally create mediator which will link TabLayout with ViewPager
- The mediator will synchronize the ViewPager2's position with the selected tab when a tab is selected, and the TabLayout's scroll position when the user drags the ViewPager
- Set