Home Ask Login Register

Developers Planet

Your answer is one click away!

texas February 2016

Scroll Images Horizontally with Page Indicator

I am trying to implement a feature where user could able to scroll the images from left to right or from right to left. Since Gallery class has been deprecated, I have added a TouchListener on the ImageView and implemented the following method to find out touch direction as follows. I have also added radio button group to give a sense of page indicator.

It is working and functional, but I wonder is there any drawbacks of my approach? Any recommendation?

public class SwipeListener implements View.OnTouchListener {
    private int min_distance = 100;
    private float downX, downY, upX, upY;
    View v;

    public boolean onTouch(View v, MotionEvent event) {
        this.v = v;
        switch(event.getAction()) { // Check vertical and horizontal touches
            case MotionEvent.ACTION_DOWN: {
                downX = event.getX();
                downY = event.getY();
                return true;
            case MotionEvent.ACTION_UP: {
                upX = event.getX();
                upY = event.getY();

                float deltaX = downX - upX;
                float deltaY = downY - upY;

                //HORIZONTAL SCROLL
                if (Math.abs(deltaX) > Math.abs(deltaY)) {
                    if (Math.abs(deltaX) > min_distance) {
                        // left or right
                        if (deltaX < 0) {
                            return true;
                        if (deltaX > 0) {
                            return true;
                    } else {
                        //not long enough swipe...
                        return false;
        return false;

    public void onLeftToRightSwipe(){


Jadav Lalit February 2016

You can use viewpager. Add this in your xml file

    android:layout_height="match_parent" />

and this in your class file

private ViewPager mPager;
private PagerAdapter mPagerAdapter;

in onCreate method add this code

mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());

And add this class as subclass in your main class.

private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {

        public Fragment getItem(int position) {
                 case 0:
                   return new ScreenSlidePageFragment();
                 case 1:
                   return new ScreenSlidePageFragment1();


        public int getCount() {
            return NUM_PAGES;

Post Status

Asked in February 2016
Viewed 2,391 times
Voted 14
Answered 1 times


Leave an answer

Quote of the day: live life