Android ViewPager(2) with dots indicator
Implementation of dots indicator for ViewPager without any 3rd party libraries. All we need are: ViewPager, TabLayout and 2 drawables for selected and default dots.
Implementation for ViewPager2
is almost the same:
Replace androidx.viewpager.widget.ViewPager
with androidx.viewpager2.widget.ViewPager2
.
Firstly, we have to add TabLayout
to our screen layout, and connect it with ViewPager
. We can do this in two ways:
Using nested TabLayout
inside ViewPager
TabLayout
supports being used as part of a ViewPager’s decor, and can be added directly to the ViewPager in a layout resource file like so:
Views which are annotated with the
ViewPager.DecorView
annotation are treated as part of the view pagers 'decor'. Each decor view's position can be controlled via itsandroid:layout_gravity
attribute.
Separate TabLayout
We don’t have to place TabLayout inside ViewPager, we can put it elsewhere:
In this case we have to connect TabLayout
with ViewPager
programmatically:
for ViewPager
by using setupWithViewPager(viewPager)
method:
for ViewPager2
by using TabLayoutMediator
:
Once we created our layout, we have to prepare our dots. So we create three files: selected_dot.xml
, default_dot.xml
and tab_selector.xml
.
selected_dot.xml
default_dot.xml
tab_selector.xml
This file will switch between selected_dot.xml
and default_dot.xml
, depending on the page selected in ViewPager
In the last step, we need to connect tab_selector
with TabLayout
, to do this we have to add only 3 lines of code to our TabLayout
in xml:
app:tabBackground="@drawable/tab_selector"
app:tabGravity="center"
app:tabIndicatorHeight="0dp"
DONE! 👏👏👏
Here is code example of dots indicator for ViewPager
and ViewPager2