Android view pager change pages automatically after a few seconds
Asked Answered
H

4

14

I have used android view pager to display images and text now what i want is that if a user is not changing the images then it should start to change the images automatically after a few seconds and when the user again starts using his finger then the images should not change automatically?

I tried to use the handler to create a delay but it did not worked for me?

Please help anyone

public class SimpleImageViewerActivity  extends Activity implements ViewPager.OnPageChangeListener{
    private Handler handler;
    ViewPager myPager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.imageslideshow);
        MyPagerAdapter adapter = new MyPagerAdapter();
        myPager = (ViewPager) findViewById(R.id.slideShowPager);
        myPager.setAdapter(adapter);
        myPager.setCurrentItem(0);

        handler = new Handler();
    myPager.setOnPageChangeListener(this);
    }

    private class MyPagerAdapter extends PagerAdapter {

        public int getCount() {
            return 5;
        }

        public Object instantiateItem(View collection, int position) {

            LayoutInflater inflater = (LayoutInflater) collection.getContext()
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            int resId = 0;
            switch (position) {
            case 0:
                resId = R.layout.farleft;
                break;
            case 1:
                resId = R.layout.left;
                break;
            case 2:
                resId = R.layout.middle;
                break;
            case 3:
                resId = R.layout.right;
                break;
            case 4:
                resId = R.layout.farright;
                break;
            }

            View view = inflater.inflate(resId, null);

            ((ViewPager) collection).addView(view, 0);

            return view;
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView((View) arg2);

        }

        @Override
        public void finishUpdate(View arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == ((View) arg1);

        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
            // TODO Auto-generated method stub

        }

        @Override
        public Parcelable saveState() {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
            // TODO Auto-generated method stub

        }


    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
        // TODO Auto-generated method stub

        updateUI(arg2);
    }

    @Override
    public void onPageSelected(int arg0) {
        // TODO Auto-generated method stub
        //updateUI(arg0);

    }

    public void onNothingSelected(AdapterView<?> adapterView) {    
        final int i =0;
        adapterView.postDelayed(new Runnable(){

            @Override
            public void run() {
                // TODO Auto-generated method stub
                updateUI(i);            
            }

        }, 5000);
        Toast.makeText(this, "In nothing selected method",Toast.LENGTH_SHORT).show();




    }

    private void updateUI(final int fi) {
           /* handler.post(new Runnable() {
                public void run() {
                    gallery.setSelection(i);
                    viewPager.setCurrentItem(i);

                    //textView.setText("Photo #" + i);
                }
            });*/
            handler.postDelayed(new Runnable() {
                public void run() {
                    int i=fi;
                    int j = i;
                    myPager.setCurrentItem(j++);
                    System.out.println("Hello");             

                }
            },1000);
        }   


}
Heinous answered 6/4, 2012 at 10:56 Comment(4)
try with ViewSwitcher. Design your page and call its method next() after few second..\Thrush
can you please given an example or a code snippet?Heinous
hey buddy, i have implemented this scenario if u need it just let me know i'll post the solution hereIntercessor
@Intercessor can you please post the solution here using ViewPagerPostprandial
G
4

Use javautil timer and set one up and at the end of timer you can use

class UpdateTimeTask extends TimerTask {
   public void run() {
    //Code for the viewPager to change view
  }
 }


 // Code to schedule the timer
 timer = new Timer();
 timer.schedule(new UpdateTimeTask(), 100, 200);

Hope this helps, use the android docs for exact API calls

<ViewPager>.setCurrentitem(i++%<MaxViews>)
Giulietta answered 6/4, 2012 at 11:12 Comment(2)
Tried that onCreate (activity) and java.lang.IllegalStateException: Must be called from main thread of process :/Arva
Check out this answer on stackoverflow: https://mcmap.net/q/534245/-how-to-switch-automatically-between-viewpager-pagesWeissman
J
0

As far as UI update is concerned you can do it via handler, So call a handler inside timertask class, you can do something like this :

Timer timer=null;
static int time_tomove = 0;

class UpdateTimeTask extends TimerTask {
       public void run() {
        //Code for the viewPager to change view
           System.out.println("The value of the time_tomove ");
           time_tomove++;
           Message msg = handler_timer.obtainMessage();
            Bundle b = new Bundle();
            b.putInt("time", time_tomove);
            msg.setData(b);
            handler_timer.sendMessage(msg);
      }
     }




public static Handler handler_timer = new Handler(){
    @Override
    public void handleMessage(Message msg) {
        super.handleMessage(msg);
    magazineHolder.setCurrentItem(time_tomove);
    }
};

After doing this you can call the below two lines inside either your onresume or oncreate() method

timer = new Timer();
         timer.schedule(new UpdateTimeTask(), 100, 2000);
Jessie answered 29/1, 2014 at 13:36 Comment(0)
R
0

Kotlin way

This is from a Fragment context, remove requireActivity() if you are in an Activity

private var timer: Timer? = null
private var page = 0
private var maxPages = 4

   // Use this method to setup your viewpager in your onCreate() or onActivityCreated() methods
   fun setupViewPager(){
    viewPager2.adapter = MyAdapter()
    viewPager2.isUserInputEnabled = false
    pageSwitcher(5)
}

fun pageSwitcher(seconds: Int) {
    timer = Timer()
    timer!!.scheduleAtFixedRate(RemindTask(), 0, seconds * 1000.toLong())
}

class RemindTask:TimerTask(){

        override fun run() {
            requireActivity().runOnUiThread {
                if(page == maxPages){
                    page = 0
                }else{
                    viewPager2.setCurrentItem(page++,true)
                }
            }
        }
    }
Redtop answered 22/1, 2020 at 17:54 Comment(0)
S
0

Short and simple Extension for kotlin

private fun ViewPager2.postDelayScroll(totalPages: Int): Timer {
    val timer = Timer()
    var currentPage =0
    timer.schedule(object : TimerTask() {
        override fun run() {
            handler.post {
                if ( currentItem == totalPages -1) {
                    currentPage = 0;
                }
                [email protected](currentPage++, true);
            }
        }
    },100,1000 * DELAY_IN_SECONDS)
    return timer
}
Skunk answered 10/5 at 12:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.