Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto slide android View Pager

Can a View Pager be made to auto slide or autopage. I have my viewpager set up to use the adapter like the below and it works fine:-

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.gridslide);
ImagePagerAdapter mAdapter = new ImagePagerAdapter(
        getSupportFragmentManager(),4);
ViewPager mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}

And the adapter is like below:-

public static class ImagePagerAdapter extends FragmentStatePagerAdapter {
private final int mSize;

public ImagePagerAdapter(FragmentManager fm, int size) {
    super(fm);
    mSize = size;
}

@Override
public int getCount() {
    return mSize;
}
@Override
public Fragment getItem(int position) {
    Log.v(TAG,"position="+position);
    return TheFragment.newInstance(position);
}}

However I would want to know how to make these fragments autoslide in a viewpager.

like image 996
Rasmus Avatar asked Jul 28 '12 06:07

Rasmus


1 Answers

short answer 2020

After you set your viewPager adapter

   private Runnable runnable = null;
  
   public void function DisplaySlider(){

    sliderItemAdapter = new SliderItemAdapter(getActivity(), mSliderList);//push the data to the adapter
    mViewPager.setAdapter(sliderItemAdapter); //set the adapter to the view pager
    startAutoSlider(sliderItem.getCount());

   }


     

private void startAutoSlider(final int count) {

    runnable = new Runnable() {
        @Override
        public void run() {
            int pos = mViewPager.getCurrentItem();
            pos = pos + 1;
            if (pos >= count) pos = 0;
            mViewPager.setCurrentItem(pos);
            handler.postDelayed(runnable, 3000);
        }
    };
    handler.postDelayed(runnable, 3000);
}

   

And finally don`t forget to free the memory from the callbacks

@Override
public void onDestroy() {
    if (runnable != null) handler.removeCallbacks(runnable);
    super.onDestroy();
}
like image 135
Mohamed Ayed Avatar answered Oct 18 '22 17:10

Mohamed Ayed