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.

default_indicator.xml
<?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>

indicator_selector.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemxmlas.android.com/apk/res/android">

    <item android:drawable="@drawable/selected_indicator"
        android:state_selected="true"/>

    <item android:drawable="@drawable/default_indicator"/>
</selector>

selected_indicator.xml
<?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="@color/colorAccent"/>
        </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.

item_slider.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"xm
    android:layout_height="match_parent"
    android:gravity="center"
    android:id="@+id/linearLayout"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/white"
        android:textSize="20sp" />

</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.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/parent"
    android:background="#10101C"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <android.support.design.widget.TabLayout
        android:id="@+id/indicator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        app:tabBackground="@drawable/indicator_selector"
        app:tabGravity="center"
        app:tabIndicatorHeight="0dp" />
</RelativeLayout>

Now moving to java part, initialize our viewpager and tablayout

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);
        }
}

Next we need to create an adapter class named SliderAdapter (ofcourse you can name as you like).

SliderAdapter.java
package com.techpakka.tutorials;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.List;

public class SliderAdapter extends PagerAdapter {
    private Context context;
    private List<Integer> color;
    private List<String> colorName;

    public SliderAdapter(Context context, List<Integer> color, List<String> colorName) {
        this.context = context;
        this.color = color;
        this.colorName = colorName;
    }

    @Override
    public int getCount() {
        return color.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object o) {
        return view == o;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.item_slider,null);

        TextView textView = (TextView) view.findViewById(R.id.textView);
        LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.linearLayout);
        textView.setText(colorName.get(position));
        linearLayout.setBackgroundColor(color.get(position));
        ViewPager viewPager = (ViewPager) container;
        viewPager.addView(view, 0);

        return view;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        ViewPager viewPager = (ViewPager) container;
        View view = (View) object;
        viewPager.removeView(view);
    }
}

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.

Last updated