14

I am trying to implement a simple gallery of images in which I have an image to be displayed at a time on the device screen. When we swipe the screen from left to right it should show the next image.
For that I implemented a view flipper and added image views to it.
But I don't know how to catch that swipe event.
Can anyone tell me with an example?

2
  • And why would you want to catch that swipe event?
    – Aman Aalam
    Commented Feb 24, 2011 at 7:35
  • i want to catch that swipe event so that based on the swipe i can change the images from left to right or vice versa Commented Feb 24, 2011 at 8:01

7 Answers 7

17

I needed the same thing for my app, and used a ViewPager: http://blog.sqisland.com/2012/09/android-swipe-image-viewer-with-viewpager.html

Previously I used a ImageSwitcher combined with a GestureDetector: http://blog.sqisland.com/2012/07/android-swipe-image-viewer.html

The code with ViewPager is much simpler, and the experience is much better because the image slides as your finger swipe across the screen. I create ImageView directly, no fragments required.

1
  • This should be the accepted answer! You just made my day with your solution and saved me hours of labor. Thank you so much!!!
    – Emzor
    Commented Feb 9, 2016 at 10:25
5

You can create a custom Pager Adapter for your ViewPager:

public class ImageAdapter extends PagerAdapter {
    private Context context;
    private int[] GalImages = new int[]{
            R.drawable.cap8, R.drawable.cap2, R.drawable.cap3, R.drawable.cap1, R.drawable.cap5,
            R.drawable.cap6, R.drawable.cap7, R.drawable.cap9, R.drawable.cap4,
            R.drawable.cap10

    };

    ImageAdapter(Context context) {
        this.context = context;
    }

    @Override
    public int getCount() {
        return GalImages.length;
    }

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

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        ImageView imageView = new ImageView(context);
        int padding = context.getResources().getDimensionPixelSize(R.dimen.activity_horizontal_margin);
        imageView.setPadding(padding, padding, padding, padding);
        imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
        imageView.setImageResource(GalImages[position]);
        container.addView(imageView, 0);
        return imageView;
    }

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

Use the ViewPager in your layout and register the adapter:

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

You can do like this way also, without using view flipper

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

<ImageView
                 android:layout_width="match_parent"
                 android:layout_height="match_parent"
                 android:layout_gravity="center"
                 android:gravity="center"
                 android:layout_margin="10dip"
                 android:id="@+id/image_place_holder"
                 />

 </RelativeLayout>

Activity Class

 public class MainActivity extends Activity  {

 private Integer[] mImageIds = { R.drawable.img1, R.drawable.img2,R.drawable.img3 };

private static final String DEBUG_TAG = "MainActivity ";
ImageView imageView;
float startXValue = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.gallery);
    imageView = (ImageView) findViewById(R.id.image_place_holder);
    imageView.setImageResource(mImageIds[num]);
}

@Override
public boolean onTouchEvent(MotionEvent event) {    
    float endXValue = 0;
    float x1 = event.getAxisValue(MotionEvent.AXIS_X);
    int action = MotionEventCompat.getActionMasked(event);
    switch (action) {
        case (MotionEvent.ACTION_DOWN):
            startXValue = event.getAxisValue(MotionEvent.AXIS_X);

            return true;

        case (MotionEvent.ACTION_UP):
            endXValue = event.getAxisValue(MotionEvent.AXIS_X);
            if (endXValue > startXValue) {
                if (endXValue - startXValue > 100) {
                System.out.println("Left-Right");
                imageView.setImageResource(mImageIds[2]);
                }
            }else {
                if (startXValue -endXValue> 100) {
                System.out.println("Right-Left");
                imageView.setImageResource(mImageIds[0]);

                     }
                         }
        return true;


           default:
        return super.onTouchEvent(event);
     }

}

}
1

You want to use a ViewPager available in the Android Support Jar. Here is a tutorial: http://thepseudocoder.wordpress.com/2011/10/05/android-page-swiping-using-viewpager/

You dont want use Gallery as some suggest as its not deprecated. However from the documentation they suggest the ViewPager and HorizantleScrollView to solve this problem relatively easily:

This class is deprecated.
    This widget is no longer supported. Other horizontally scrolling widgets include
    HorizontalScrollView and ViewPager from the support library.
1
  • IMO ViewPager is not appropriate in all cases. It's associated generally with fragments, and if you only want to swipe images using a separate fragment with each swipe seems overkill
    – Jose_GD
    Commented Aug 9, 2012 at 17:28
1

You can do like that,It surly works without any view

public class Swipe extends Activity implements OnClickListener {

private static final int SWIPE_MIN_DISTANCE = 120;
//private static final int SWIPE_MAX_OFF_PATH = 250;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
final GestureDetector gdt = new GestureDetector(new GestureListener());
private GestureDetector gestureDetector;
ImageView img;


View.OnTouchListener gestureListener;

@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.swipe);
    img = (ImageView)findViewById(R.id.imageView1swipe);

    img.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(final View view, final MotionEvent event) {
            // TODO Auto-generated method stub
            gdt.onTouchEvent(event);
            //Log.i("Hello my Log 1","How dfgfd are you");
            return true;
        }
    });

and declare this method in your .java

private class GestureListener extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                float velocityY) {
            Log.i("Hello my Log 2","How dfgfd are you");
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

                Log.i("dfsd", "Right to left");
                return false; // Right to left
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                return false; // Left to right
            }

            if (e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                return false; // Bottom to top
            } else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
                return false; // Top to bottom
            }

            return false;
        }'

May be this will help you for arranging all the swiping of Images

1
1

This is how i achieved:

package com.demoimageslider;

import java.util.List;
import java.util.Vector;

import com.nineoldandroids.view.ViewHelper;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

public class MainActivity extends FragmentActivity {

    private PagerAdapter mPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.initialisePaging();
    }

    private void initialisePaging() {

        List<Fragment> fragments = new Vector<Fragment>();
        fragments.add(Fragment.instantiate(this, Tab1Fragment.class.getName()));
        fragments.add(Fragment.instantiate(this, Tab2Fragment.class.getName()));
        fragments.add(Fragment.instantiate(this, Tab3Fragment.class.getName()));
        this.mPagerAdapter = new PagerAdapter(
                super.getSupportFragmentManager(), fragments);

        ViewPager pager = (ViewPager) super.findViewById(R.id.pager);
        pager.setAdapter(this.mPagerAdapter);
        pager.setPageTransformer(true, new ZoomOutPageTransformer());
    }

    public static class Tab1Fragment extends Fragment {

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            if (container == null) {
                return null;
            }
            return (ImageView) inflater.inflate(R.layout.tab_frag1_layout,
                    container, false);
        }
    }

    public static class Tab2Fragment extends Fragment {

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            if (container == null) {
                return null;
            }
            return (ImageView) inflater.inflate(R.layout.tab_frag2_layout,
                    container, false);
        }
    }

    public static class Tab3Fragment extends Fragment {

        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            if (container == null) {
                return null;
            }
            return (ImageView) inflater.inflate(R.layout.tab_frag3_layout,
                    container, false);
        }
    }

    public static class PagerAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragments;

        public PagerAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }

        @Override
        public Fragment getItem(int position) {
            return this.fragments.get(position);
        }

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

    public static class ZoomOutPageTransformer implements
            ViewPager.PageTransformer {
        private static final float MIN_SCALE = 0.85f;
        private static final float MIN_ALPHA = 0.5f;

        public void transformPage(View view, float position) {
            int pageWidth = view.getWidth();
            int pageHeight = view.getHeight();

            if (position < -1) { // [-Infinity,-1)
                // This page is way off-screen to the left.
                // view.setAlpha(0);
                ViewHelper.setAlpha(view, 0);

            } else if (position <= 1) { // [-1,1]
                // Modify the default slide transition to shrink the page as
                // well
                float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
                float vertMargin = pageHeight * (1 - scaleFactor) / 2;
                float horzMargin = pageWidth * (1 - scaleFactor) / 2;
                if (position < 0) {
                    // view.setTranslationX(horzMargin - vertMargin / 2);
                    ViewHelper.setTranslationX(view, horzMargin - vertMargin
                            / 2);
                } else {
                    // view.setTranslationX(-horzMargin + vertMargin / 2);
                    ViewHelper.setTranslationX(view, -horzMargin + vertMargin
                            / 2);
                }

                // Scale the page down (between MIN_SCALE and 1)
                // view.setScaleX(scaleFactor);
                // view.setScaleY(scaleFactor);
                ViewHelper.setScaleX(view, scaleFactor);
                ViewHelper.setScaleY(view, scaleFactor);

                // Fade the page relative to its size.
                // view.setAlpha(MIN_ALPHA +
                // (scaleFactor - MIN_SCALE) /
                // (1 - MIN_SCALE) * (1 - MIN_ALPHA));

                ViewHelper.setAlpha(view, MIN_ALPHA + (scaleFactor - MIN_SCALE)
                        / (1 - MIN_SCALE) * (1 - MIN_ALPHA));

            } else { // (1,+Infinity]
                // This page is way off-screen to the right.
                // view.setAlpha(0);
                ViewHelper.setAlpha(view, 0);
            }
        }
    }
}

I used nineoldroids library to support effects on older android versions.

0

Why don't you implement it using gallery widget?

Here is the gallery tutorial.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.