32

Hi I am new in android and in my app I have a lot of images in my ArrayList that 's why I want to swipe those images automatically for every 3 seconds with help of Timetasker and this process is continuously need to repeating up to we close app. Can some body help me please

MainActivity:-

public class MainActivity extends AppCompatActivity {

    ViewPager viewPager;

    Integer[] imageId = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};
    String[] imagesName = {"image1","image2","image3","image4"};

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

        viewPager = (ViewPager) findViewById(R.id.viewPager);
        PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
        viewPager.setAdapter(adapter);
    }
}

CustomAdapter:-

public class CustomAdapter extends PagerAdapter{

    private Activity activity;
    private Integer[] imagesArray;
    private String[] namesArray;

    public CustomAdapter(Activity activity,Integer[] imagesArray,String[] namesArray){

        this.activity = activity;
        this.imagesArray = imagesArray;
        this.namesArray = namesArray;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {

        LayoutInflater inflater = ((Activity)activity).getLayoutInflater();

        View viewItem = inflater.inflate(R.layout.image_item, container, false);
        ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
        imageView.setImageResource(imagesArray[position]);
        TextView textView1 = (TextView) viewItem.findViewById(R.id.textview);
        textView1.setText(namesArray[position]);
        ((ViewPager)container).addView(viewItem);

        return viewItem;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return imagesArray.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        // TODO Auto-generated method stub
        return view == ((View)object);
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        // TODO Auto-generated method stub
        ((ViewPager) container).removeView((View) object);
    }
}
P R
  • 105
  • 9
Krish
  • 4,166
  • 11
  • 58
  • 110

14 Answers14

90

Your question is already answered here

Add this in your MainActivity.java

//...   
int currentPage = 0;
Timer timer;
final long DELAY_MS = 500;//delay in milliseconds before task is to be executed
final long PERIOD_MS = 3000; // time in milliseconds between successive task executions.


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

    viewPager = (ViewPager) findViewById(R.id.viewPager);
    PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
    viewPager.setAdapter(adapter);

    /*After setting the adapter use the timer */
    final Handler handler = new Handler();
    final Runnable Update = new Runnable() {
        public void run() {
            if (currentPage == NUM_PAGES-1) {
                currentPage = 0;
            }
            viewPager.setCurrentItem(currentPage++, true);
         }
     };

    timer = new Timer(); // This will create a new Thread 
    timer.schedule(new TimerTask() { // task to be scheduled
        @Override
        public void run() {
            handler.post(Update);
        }
    }, DELAY_MS, PERIOD_MS);
}
Sanjeev
  • 4,255
  • 3
  • 28
  • 37
R.K
  • 1,721
  • 17
  • 22
  • feel free to ask any questions in the comment – R.K Jul 20 '16 at 05:57
  • what is this currentPage and NUM_PAGES – Krish Jul 20 '16 at 06:22
  • currentPage is which page you are currently at. and NUM_PAGES is total number of pages.. in your case its 4 – R.K Jul 20 '16 at 06:27
  • The code you provided does not reset the timer. I mean when the last page is come up it stops working. It's supposed to run timer again and again... @R.K – inverted_index Jul 30 '17 at 07:07
  • you forgot to use DELAY_MS and PERIOD_MS in your method – temirbek Aug 25 '17 at 10:30
  • @inverted_index... Hey buddy, the code does return back to the 1st slide from last page. You might have missed the code: "if (currentPage == NUM_PAGES-1) { currentPage = 0; } " – R.K Aug 27 '17 at 08:53
  • I have 4 images scrolling. When once the scrolling is done. It comes to first image where there is a blank page is appearing on which images gets loaded. It is happening with first image only. Any idea? – AkshayT Feb 13 '18 at 10:11
  • The screens are moving too fast. How do I ensure that there is a slow transition from one screen to another? – Yesha Jun 26 '18 at 10:18
  • @Yesha... You can increase the value for PERIOD_MS in milliseconds. – R.K Jun 27 '18 at 14:45
  • When once the scrolling is done and move to pager moving fist page it's look like restat agin how to solve this weird user experience. Note:View pager with auto change working perfect (Y) just remove that – Arbaz.in Sep 10 '20 at 06:39
  • `NUM_PAGES-1` should be only `NUM_PAGES` otherwise it will skip the last page. – Pratik Butani Oct 15 '20 at 06:45
28

Here is the code for the automatic scroll the viewpager item:

public class MainActivity extends AppCompatActivity {

    AutoScrollViewPager viewPager;

    Integer[] imageId = {R.drawable.commitementlogo, R.drawable.like, R.drawable.like_select, R.drawable.plus};
    String[] imagesName = {"image1","image2","image3","image4"};

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

        viewPager= (AutoScrollViewPager) findViewById(R.id.viewpager);
        viewPager.startAutoScroll();
        viewPager.setInterval(3000);
        viewPager.setCycle(true);
        viewPager.setStopScrollWhenTouch(true);

        PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
        viewPager.setAdapter(adapter);

    }


}

Here AutoscrollViewpager class:

public class AutoScrollViewPager extends ViewPager {

    public static final int        DEFAULT_INTERVAL            = 1500;

    public static final int        LEFT                        = 0;
    public static final int        RIGHT                       = 1;

    /** do nothing when sliding at the last or first item **/
    public static final int        SLIDE_BORDER_MODE_NONE      = 0;
    /** cycle when sliding at the last or first item **/
    public static final int        SLIDE_BORDER_MODE_CYCLE     = 1;
    /** deliver event to parent when sliding at the last or first item **/
    public static final int        SLIDE_BORDER_MODE_TO_PARENT = 2;

    /** auto scroll time in milliseconds, default is {@link #DEFAULT_INTERVAL} **/
    private long                   interval                    = DEFAULT_INTERVAL;
    /** auto scroll direction, default is {@link #RIGHT} **/
    private int                    direction                   = RIGHT;
    /** whether automatic cycle when auto scroll reaching the last or first item, default is true **/
    private boolean                isCycle                     = true;
    /** whether stop auto scroll when touching, default is true **/
    private boolean                stopScrollWhenTouch         = true;
    /** how to process when sliding at the last or first item, default is {@link #SLIDE_BORDER_MODE_NONE} **/
    private int                    slideBorderMode             = SLIDE_BORDER_MODE_NONE;
    /** whether animating when auto scroll at the last or first item **/
    private boolean                isBorderAnimation           = true;
    /** scroll factor for auto scroll animation, default is 1.0 **/
    private double                 autoScrollFactor            = 1.0;
    /** scroll factor for swipe scroll animation, default is 1.0 **/
    private double                 swipeScrollFactor           = 1.0;

    private Handler handler;
    private boolean                isAutoScroll                = false;
    private boolean                isStopByTouch               = false;
    private float                  touchX                      = 0f, downX = 0f;
    private CustomDurationScroller scroller                    = null;

    public static final int        SCROLL_WHAT                 = 0;

    public AutoScrollViewPager(Context paramContext) {
        super(paramContext);
        init();
    }

    public AutoScrollViewPager(Context paramContext, AttributeSet paramAttributeSet) {
        super(paramContext, paramAttributeSet);
        init();
    }

    private void init() {
        handler = new MyHandler(this);
        setViewPagerScroller();
    }

    /**
     * start auto scroll, first scroll delay time is {@link #getInterval()}
     */
    public void startAutoScroll() {
        isAutoScroll = true;
        sendScrollMessage((long)(interval + scroller.getDuration() / autoScrollFactor * swipeScrollFactor));
    }

    /**
     * start auto scroll
     * 
     * @param delayTimeInMills first scroll delay time
     */
    public void startAutoScroll(int delayTimeInMills) {
        isAutoScroll = true;
        sendScrollMessage(delayTimeInMills);
    }

    /**
     * stop auto scroll
     */
    public void stopAutoScroll() {
        isAutoScroll = false;
        handler.removeMessages(SCROLL_WHAT);
    }

    /**
     * set the factor by which the duration of sliding animation will change while swiping
     */
    public void setSwipeScrollDurationFactor(double scrollFactor) {
        swipeScrollFactor = scrollFactor;
    }

    /**
     * set the factor by which the duration of sliding animation will change while auto scrolling
     */
    public void setAutoScrollDurationFactor(double scrollFactor) {
        autoScrollFactor = scrollFactor;
    }

    private void sendScrollMessage(long delayTimeInMills) {
        /** remove messages before, keeps one message is running at most **/
        handler.removeMessages(SCROLL_WHAT);
        handler.sendEmptyMessageDelayed(SCROLL_WHAT, delayTimeInMills);
    }

    /**
     * set ViewPager scroller to change animation duration when sliding
     */
    private void setViewPagerScroller() {
        try {
            Field scrollerField = ViewPager.class.getDeclaredField("mScroller");
            scrollerField.setAccessible(true);
            Field interpolatorField = ViewPager.class.getDeclaredField("sInterpolator");
            interpolatorField.setAccessible(true);

            scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));
            scrollerField.set(this, scroller);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * scroll only once
     */
    public void scrollOnce() {
        PagerAdapter adapter = getAdapter();
        int currentItem = getCurrentItem();
        int totalCount;
        if (adapter == null || (totalCount = adapter.getCount()) <= 1) {
            return;
        }

        int nextItem = (direction == LEFT) ? --currentItem : ++currentItem;
        if (nextItem < 0) {
            if (isCycle) {
                setCurrentItem(totalCount - 1, isBorderAnimation);
            }
        } else if (nextItem == totalCount) {
            if (isCycle) {
                setCurrentItem(0, isBorderAnimation);
            }
        } else {
            setCurrentItem(nextItem, true);
        }
    }

    /**
     * <ul>
     * if stopScrollWhenTouch is true
     * <li>if event is down, stop auto scroll.</li>
     * <li>if event is up, start auto scroll again.</li>
     * </ul>
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int action = ev.getActionMasked();

        if (stopScrollWhenTouch) {
            if ((action == MotionEvent.ACTION_DOWN) && isAutoScroll) {
                isStopByTouch = true;
                stopAutoScroll();
            } else if (ev.getAction() == MotionEvent.ACTION_UP && isStopByTouch) {
                startAutoScroll();
            }
        }

        if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT || slideBorderMode == SLIDE_BORDER_MODE_CYCLE) {
            touchX = ev.getX();
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                downX = touchX;
            }
            int currentItem = getCurrentItem();
            PagerAdapter adapter = getAdapter();
            int pageCount = adapter == null ? 0 : adapter.getCount();
            /**
             * current index is first one and slide to right or current index is last one and slide to left.<br/>
             * if slide border mode is to parent, then requestDisallowInterceptTouchEvent false.<br/>
             * else scroll to last one when current item is first one, scroll to first one when current item is last
             * one.
             */
            if ((currentItem == 0 && downX <= touchX) || (currentItem == pageCount - 1 && downX >= touchX)) {
                if (slideBorderMode == SLIDE_BORDER_MODE_TO_PARENT) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                } else {
                    if (pageCount > 1) {
                        setCurrentItem(pageCount - currentItem - 1, isBorderAnimation);
                    }
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                return super.dispatchTouchEvent(ev);
            }
        }
        getParent().requestDisallowInterceptTouchEvent(true);

        return super.dispatchTouchEvent(ev);
    }

    private static class MyHandler extends Handler {

        private final WeakReference<AutoScrollViewPager> autoScrollViewPager;

        public MyHandler(AutoScrollViewPager autoScrollViewPager) {
            this.autoScrollViewPager = new WeakReference<AutoScrollViewPager>(autoScrollViewPager);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case SCROLL_WHAT:
                    AutoScrollViewPager pager = this.autoScrollViewPager.get();
                    if (pager != null) {
                        pager.scroller.setScrollDurationFactor(pager.autoScrollFactor);
                        pager.scrollOnce();
                        pager.scroller.setScrollDurationFactor(pager.swipeScrollFactor);
                        pager.sendScrollMessage(pager.interval + pager.scroller.getDuration());
                    }
                default:
                    break;
            }
        }
    }

    /**
     * get auto scroll time in milliseconds, default is {@link #DEFAULT_INTERVAL}
     * 
     * @return the interval
     */
    public long getInterval() {
        return interval;
    }

    /**
     * set auto scroll time in milliseconds, default is {@link #DEFAULT_INTERVAL}
     * 
     * @param interval the interval to set
     */
    public void setInterval(long interval) {
        this.interval = interval;
    }

    /**
     * get auto scroll direction
     * 
     * @return {@link #LEFT} or {@link #RIGHT}, default is {@link #RIGHT}
     */
    public int getDirection() {
        return (direction == LEFT) ? LEFT : RIGHT;
    }

    /**
     * set auto scroll direction
     * 
     * @param direction {@link #LEFT} or {@link #RIGHT}, default is {@link #RIGHT}
     */
    public void setDirection(int direction) {
        this.direction = direction;
    }

    /**
     * whether automatic cycle when auto scroll reaching the last or first item, default is true
     * 
     * @return the isCycle
     */
    public boolean isCycle() {
        return isCycle;
    }

    /**
     * set whether automatic cycle when auto scroll reaching the last or first item, default is true
     * 
     * @param isCycle the isCycle to set
     */
    public void setCycle(boolean isCycle) {
        this.isCycle = isCycle;
    }

    /**
     * whether stop auto scroll when touching, default is true
     * 
     * @return the stopScrollWhenTouch
     */
    public boolean isStopScrollWhenTouch() {
        return stopScrollWhenTouch;
    }

    /**
     * set whether stop auto scroll when touching, default is true
     * 
     * @param stopScrollWhenTouch
     */
    public void setStopScrollWhenTouch(boolean stopScrollWhenTouch) {
        this.stopScrollWhenTouch = stopScrollWhenTouch;
    }

    /**
     * get how to process when sliding at the last or first item
     * 
     * @return the slideBorderMode {@link #SLIDE_BORDER_MODE_NONE}, {@link #SLIDE_BORDER_MODE_TO_PARENT},
     *         {@link #SLIDE_BORDER_MODE_CYCLE}, default is {@link #SLIDE_BORDER_MODE_NONE}
     */
    public int getSlideBorderMode() {
        return slideBorderMode;
    }

    /**
     * set how to process when sliding at the last or first item
     * 
     * @param slideBorderMode {@link #SLIDE_BORDER_MODE_NONE}, {@link #SLIDE_BORDER_MODE_TO_PARENT},
     *        {@link #SLIDE_BORDER_MODE_CYCLE}, default is {@link #SLIDE_BORDER_MODE_NONE}
     */
    public void setSlideBorderMode(int slideBorderMode) {
        this.slideBorderMode = slideBorderMode;
    }

    /**
     * whether animating when auto scroll at the last or first item, default is true
     * 
     * @return
     */
    public boolean isBorderAnimation() {
        return isBorderAnimation;
    }

    /**
     * set whether animating when auto scroll at the last or first item, default is true
     * 
     * @param isBorderAnimation
     */
    public void setBorderAnimation(boolean isBorderAnimation) {
        this.isBorderAnimation = isBorderAnimation;
    }
}

here CustomDurationScroller class:

public class CustomDurationScroller extends Scroller {

    private double scrollFactor = 1;

    public CustomDurationScroller(Context context) {
        super(context);
    }

    public CustomDurationScroller(Context context, Interpolator interpolator) {
        super(context, interpolator);
    }

    public void setScrollDurationFactor(double scrollFactor) {
        this.scrollFactor = scrollFactor;
    }

    @Override
    public void startScroll(int startX, int startY, int dx, int dy, int duration) {
        super.startScroll(startX, startY, dx, dy, (int)(duration * scrollFactor));
    }
}

and set the adapter same as you previously set.

Anu Martin
  • 711
  • 1
  • 9
  • 20
sneha desai
  • 886
  • 1
  • 11
  • 19
5

Here is the total code using TimerTask:

public class MainActivity extends AppCompatActivity {

ViewPager viewPager;

Integer[] imageId = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};
String[] imagesName = {"image1","image2","image3","image4"};

Timer timer;

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

    viewPager = (ViewPager) findViewById(R.id.viewPager);
    PagerAdapter adapter = new CustomAdapter(MainActivity.this,imageId,imagesName);
    viewPager.setAdapter(adapter);

    TimerTask timerTask = new TimerTask() {
        @Override
        public void run() {
            viewPager.post(new Runnable(){

                @Override
                public void run() {
                    viewPager.setCurrentItem((viewPager.getCurrentItem()+1)%imageId.length);
                }
            });
        }
    };
    timer = new Timer();
    timer.schedule(timerTask, 3000, 3000);
}

@Override
protected void onDestroy() {
    timer.cancel();
    super.onDestroy();
}
}
L. Swifter
  • 3,179
  • 28
  • 52
  • Possible DIVIDE BY ZERO ERROR HERE ` `viewPager.setCurrentItem((viewPager.getCurrentItem()+1)%imageId.length);` when dynamically filling the imageId array. so we use `viewPager.setCurrentItem((viewPager.getCurrentItem()+1)%imageId.length+1);` – Njeru Cyrus Jun 20 '18 at 14:46
4

Create handler in activity, then schedule a task. I think Handler is enough for this small task. Don't go for timer.

Runnable timeCounter = new Runnable() {

        @Override
        public void run() {
                 if((currentIndex+1)>imageId.length() ){
                      currentIndex=0;
                  }else{
                      currentIndex++;
                 }
                ViewPager.setCurrentItem(currentIndex);
                handler.postDelayed(timeCounter, 3*1000);

        }
    };
handler.postDelayed(timeCounter, 3*1000);

then in onDestroy() or where ever you want to stop

handler.removeCallbacks(timeCounter);
Ajay Yadav
  • 312
  • 5
  • 9
Prashanth Debbadwar
  • 1,047
  • 18
  • 33
2

Another version of the answer:-

                    private int currentPage = -1;
                    // start auto scroll of viewpager
                    final Handler handler = new Handler();
                    final Runnable Update = new Runnable() {
                        public void run() {
                            viewPager.setCurrentItem(++currentPage, true);
                            // go to initial page i.e. position 0
                            if (currentPage == NUM_PAGES -1) {
                                currentPage = -1;
                                // ++currentPage will make currentPage = 0
                            }
                        }
                    };

                    timer = new Timer(); // This will create a new Thread
                    timer.schedule(new TimerTask() { // task to be scheduled

                        @Override
                        public void run() {
                            handler.post(Update);
                        }
                    }, 500, 1500);
Shubham Gupta
  • 93
  • 1
  • 4
2

a simple edit to @L. Swifter's code snippet for the ones wondering about variables, I wrapped it all in a method which you can add to your activity after setting the adapter

private void automateViewPagerSwiping() {
    final long DELAY_MS = 500;//delay in milliseconds before task is to be executed
    final long PERIOD_MS = 3000; // time in milliseconds between successive task executions.
    final Handler handler = new Handler();
    final Runnable update = new Runnable() {
        public void run() {
            if (viewPager.getCurrentItem() == adapter.getCount() - 1) { //adapter is your custom ViewPager's adapter
                viewPager.setCurrentItem(0);
            }
            else {
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
            }
        }
    };

    timer = new Timer(); // This will create a new Thread
    timer.schedule(new TimerTask() { // task to be scheduled
        @Override
        public void run() {
            handler.post(update);
        }
    }, DELAY_MS, PERIOD_MS);
}
2

using Kotlin coroutine

      val totalPages = 3

       CoroutineScope(Dispatchers.Main).launch {
        while (isActive) {
            delay(1500)
            if (viewPager.currentItem + 1 > totalPages-1) {
                viewPager.currentItem = 0
            } else {
                viewPager.currentItem++
            }
        }
    }
1

For a simple solution to show a series of images automatically try the ViewFlipper in your xml file. Not suitable for all purposes, but I found it to be a useful solution to something I was putting together.

 <ViewFlipper
android:id="@+id/viewflipper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoStart="true"
android:flipInterval="2000" >

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture1" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture2" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture3" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture4" />

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/picture5" />

PhilipS
  • 379
  • 5
  • 15
1

Auto swipe ViewPager in Kotlin, simple and easy code.(if you have only 2 page)

val handler = Handler()
val update = Runnable {
       viewPager.setCurrentItem(currentPage % 2, true);
       currentPage++
      }
var timer = Timer()// This will create a new Thread
    timer!!.schedule(object : TimerTask() {
         override fun run() {
         handler.post(update)
         }
   }, 500(DELAY_MS), 3000(PERIOD_MS))
Prashant Arvind
  • 2,139
  • 20
  • 27
0

try this code: In MainActivity -

int currentIndex=0; //for tracking current item 

Create and set your TimerTask as per your requirement then in run() of TimerTask:

public void run() {
    if((currentIndex+1)>imageId.length() ){
      currentIndex=0;
    }else{
      currentIndex++;
    }
    ViewPager.setCurrentItem(currentIndex);
}
Jaiprakash Soni
  • 4,100
  • 5
  • 36
  • 67
0
 int ci=0;
 java.util.Timer timer;
 timer=new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            viewPager.post(new Runnable() {
                @Override
                public void run() {

                    Log.d("viewPager",""+ci);
                    viewPager.setCurrentItem(ci%7);
                    ci++;

                }
            });
        }
    },1000,5000);

it updates every 5seconds(5000)

saigopi.me
  • 14,011
  • 2
  • 83
  • 54
0

You can use android TabLayout for indicators, ViewPager for slide screen and TimerTask to slide automatic

please check this link for step by step guideline and demo

CLICK HERE

Shaktisinh Jadeja
  • 1,427
  • 1
  • 17
  • 22
0

Try this in your onCreate() method

    final Handler handler = new Handler();
    Timer timer = new Timer();
    final Runnable runnable = new Runnable() {
        public void run() {
            int currentPage=viewPager.getCurrentItem();
            //return to first page, if current page is last page  
            if (currentPage == titleNames.length-1) {
                currentPage = -1;
            }
            viewPager.setCurrentItem(++currentPage, true);
        }
    };
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            handler.post(runnable);
        }
    },DELAY,PERRIOD)
-1

Try to use ViewFlipper instead of viewpager

Layout xml

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

<ViewFlipper
    android:id="@+id/imageFrames"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:drawable/screen_background_dark" >
</ViewFlipper>

<Button
    android:id="@+id/slideShowBtn"
    android:layout_width="200dp"
    android:layout_height="wrap_content"

Activity

public class SlideShowActivity extends Activity  {



ViewFlipper imageFrame;
Button slideShowBtn;
Handler handler;
Runnable runnable;
@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.photo_slideshow_main);
    imageFrame = (ViewFlipper) findViewById(R.id.imageFrames);

            //get sd card path for images

    File parentFolder = new
     File(Environment.getExternalStorageDirectory()
     .getAbsolutePath()
     + "/images");

    addFlipperImages(imageFrame, parentFolder);

    handler = new Handler();
    imageFrame.setOnClickListener(SlideShowActivity.this);

    slideShowBtn = (Button) findViewById(R.id.slideShowBtn);
    slideShowBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {

            runnable = new Runnable() {

                @Override
                public void run() {
                    handler.postDelayed(runnable, 3000);
                    imageFrame.showNext();

                }
            };
            handler.postDelayed(runnable, 500);
        }
    });

}

private void addFlipperImages(ViewFlipper flipper, File parent) {
    int imageCount = parent.listFiles().length;
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.FILL_PARENT,
            RelativeLayout.LayoutParams.FILL_PARENT);
    for (int count = 0; count < imageCount - 1; count++) {
        ImageView imageView = new ImageView(this);
        Bitmap imbm = BitmapFactory.decodeFile(parent.listFiles()[count]
                .getAbsolutePath());
        imageView.setImageBitmap(imbm);
        imageView.setLayoutParams(params);
        flipper.addView(imageView);
    }

}

}

@Override
public void onClick(View view) {

}
}
SaravInfern
  • 3,338
  • 1
  • 20
  • 44