Android ViewPager slider with indicator

Android viewpager is a widget in which user can display multiple screens in the same activity in which user can switch the screens by swiping left or right.Mainly the implementation of a viewpager will be important if the application needs tablayout which should display multiple screens. But android is not having a default widget for implementing a slider ,but we can implement slider in android with the help of a viewpager. In this tutorial we will learn how to implement a slider with indicator using a viewpager in android

Steps

  • Create a new project in android studio
  • Implement the layout for activity containing viewpager
  • Create the layout for viewpager item
  • Create the viewpager adapter
  • Implement the Activity code for setting viewpager and indicator

Create New project in android studio

Refer Android beginners app development guide if you are beginner or if you don’t know how to create project in android studio.

Implement the layout for activity containing viewpager

Once the project is created one activity with layout will be automatically created. Next step is to create the layout for the slider and indicator. For that we need to have a viewpager which will act as a slider and a layout which will be containing indicators. Following is the complete code for your layout file.

<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp">

<android.support.v4.view.ViewPager
android:id="@+id/vp_slider"
android:layout_width="match_parent"
android:layout_height="match_parent" />

<LinearLayout
android:id="@+id/ll_dots"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="20dp"
android:gravity="center"
android:orientation="horizontal"></LinearLayout>
</RelativeLayout>

Create the layout for viewpager item

Now we have the layout for the activity ,next we need to implement a layout which should be displayed inside the slider. Here i am implementing an example of a slider with just a full screen image layout ,so i will be having only a imageview inside this layout.

layout_slider.xml

<?xml version="1.0" encoding="utf-8">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">;

    <ImageView
        android:id="@+id/im_slider"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>;

</LinearLayout>

Create the adapter for viewpager

Next step is to have an adapter for the view pager. We need to provide the arraylist of images which needs to be added to the slider .From this list of images each image will be added to particular page position of the viewpager inside adapter. Following is the code for the adapter.

SliderPagerAdapter.java

public class SliderPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
    Activity activity;
    ArrayList<String> image_arraylist;

    public SliderPagerAdapter(Activity activity, ArrayList<String> image_arraylist) {
        this.activity = activity;
        this.image_arraylist = image_arraylist;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        View view = layoutInflater.inflate(R.layout.layout_slider, container, false);
        ImageView im_slider = (ImageView) view.findViewById(R.id.im_slider);
        Picasso.with(activity.getApplicationContext())
                .load(image_arraylist.get(position))
                .placeholder(R.mipmap.ic_launcher) // optional
                .error(R.mipmap.ic_launcher)         // optional
                .into(im_slider);


        container.addView(view);

        return view;
    }

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


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


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

Implement the activity code for setting viewpager and indicator

Now we have the viewpager in the layout with adapter ready to set . All you need to do is to implement the following code inside your activity’s java file . In this file we need to set the array list containing images which needs to be passed into the adapter as well as some code to auto slide the viewpager without swiping.

public class MainActivity extends AppCompatActivity{

    private ViewPager vp_slider;
    private LinearLayout ll_dots;
    SliderPagerAdapter sliderPagerAdapter;
    ArrayList<String> slider_image_list;
    private TextView[] dots;
    int page_position = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main);

// method for initialisation
        init();

// method for adding indicators
        addBottomDots(0);

        final Handler handler = new Handler();

        final Runnable update = new Runnable() {
            public void run() {
                if (page_position == slider_image_list.size()) {
                    page_position = 0;
                } else {
                    page_position = page_position + 1;
                }
                vp_slider.setCurrentItem(page_position, true);
            }
        };

        new Timer().schedule(new TimerTask() {

            @Override
            public void run() {
                handler.post(update);
            }
        }, 100, 5000);


    }

    private void init() {

        setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
        getSupportActionBar().hide();
        vp_slider = (ViewPager) findViewById(R.id.vp_slider);
        ll_dots = (LinearLayout) findViewById(R.id.ll_dots);

        slider_image_list = new ArrayList<>();

//Add few items to slider_image_list ,this should contain url of images which should be displayed in slider
// here i am adding few sample image links, you can add your own

        slider_image_list.add("http://images.all-free-download.com/images/graphiclarge/mountain_bongo_animal_mammal_220289.jpg");
        slider_image_list.add("http://images.all-free-download.com/images/graphiclarge/bird_mountain_bird_animal_226401.jpg");
        slider_image_list.add("http://images.all-free-download.com/images/graphiclarge/mountain_bongo_animal_mammal_220289.jpg");
        slider_image_list.add("http://images.all-free-download.com/images/graphiclarge/bird_mountain_bird_animal_226401.jpg");


        sliderPagerAdapter = new SliderPagerAdapter(MainActivity.this, slider_image_list);
        vp_slider.setAdapter(sliderPagerAdapter);

        vp_slider.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                addBottomDots(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void addBottomDots(int currentPage) {
        dots = new TextView[slider_image_list.size()];

        ll_dots.removeAllViews();
        for (int i = 0; i < dots.length; i++) {
            dots[i] = new TextView(this);
            dots[i].setText(Html.fromHtml("&#8226;"));
            dots[i].setTextSize(35);
            dots[i].setTextColor(Color.parseColor("#000000"));
            ll_dots.addView(dots[i]);
        }

        if (dots.length > 0)
            dots[currentPage].setTextColor(Color.parseColor("#FFFFFF"));
    }
}

Note: I am using Picasso for loading images, so we need to add picasso library in build.gradle file

compile 'com.squareup.picasso:picasso:2.3.3'

Now simply run the code .You will be able to see the viewpager slider with indicator.

About the author

Hi guys, i am the author of codesfor. I am a B.Tech graduate currently working as an App developer. Apart from job i am a blogger and a freelancer.

11 Comments

  1. suriya July 9, 2018 Reply
  2. krishnasai May 10, 2018 Reply
  3. Karan January 26, 2018 Reply
  4. Sunil Kumar January 11, 2018 Reply
    • rameesAuthor January 12, 2018 Reply
  5. Sana November 2, 2017 Reply
    • rameesAuthor November 2, 2017 Reply
  6. aaa August 26, 2017 Reply
    • rameesAuthor August 28, 2017 Reply
  7. kabilan March 31, 2017 Reply

Add a Comment

Your email address will not be published. Required fields are marked *