Android viewpager slider
A simple viewpager slider with automatic sliding views
Design library
First make sure you have added the design library
implementation 'com.android.support:design:28.0.0'You can add this library by simply copy pasting above line and paste in the application level build.gradle file located under app > build.gradle and click on the sync button on the top right corner.
Now create three drawable files default_indicator.xml, indicator_selector.xml and selected_indicator.xml under the res > drawable folder.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:innerRadius="0dp"
android:shape="ring"
android:thickness="4dp"
android:useLevel="false">
<solid android:color="@android:color/darker_gray" />
</shape>
</item>
</layer-list>We also need to create item_slider.xml which will be our layout for viewpager content. Which is simply a TextView inside a LinearLayout.
And now we have created all the necessary layout files lets move to our main activity file which is MainActivity. In its layout file activity_main.xml, add code snippet for viewpager note that we are also adding tablayout for indicators at the bottom.
Now moving to java part, initialize our viewpager and tablayout
Next we need to create an adapter class named SliderAdapter (ofcourse you can name as you like).
Lets finish this by adding some more code in MainActivity.java to get our working auto flipping viewpager slider
Explanation
First we create two arraylist color and colorNames as its name suggests color is used to set the background color for each pages in viewpager as well as colorNames are used to set value for textview.
viewPager.setAdapter is used to set the PagerAdapter, SliderAdapter.java that will supply views for this pager as needed.
indicator.setupWithViewPager is used to link the tablayout and viewpager together.
And finally we use timer.scheduleAtFixedRate to automatically flip the pages after a fixed duration by using the SliderTimer method created inside MainActivity.java.
Last updated
Was this helpful?