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.
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.
Lets finish this by adding some more code in MainActivity.java to get our working auto flipping viewpager slider
MainActivity.java
package your_package_name;
....
import android.graphics.Color;
....
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
TabLayout indicator;
List<Integer> color;
List<String> colorName;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager=(ViewPager)findViewById(R.id.viewPager);
indicator=(TabLayout)findViewById(R.id.indicator);
color = new ArrayList<>();
color.add(Color.RED);
color.add(Color.GREEN);
color.add(Color.BLUE);
colorName = new ArrayList<>();
colorName.add("RED");
colorName.add("GREEN");
colorName.add("BLUE");
viewPager.setAdapter(new SliderAdapter(this, color, colorName));
indicator.setupWithViewPager(viewPager, true);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new SliderTimer(), 4000, 6000);
}
private class SliderTimer extends TimerTask{
@Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (viewPager.getCurrentItem() < color.size() - 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
}
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.