ViewPager实现图片轮转

ViewPager实现图片轮转

viewpager的生命周期:

1:获取滑动的控件的个数。。。。getCount
2:当要缓存的图片可以进行的时候,会调用者方法进行图片的初始化,我们将要显示的View放入到ViewGroup中。然后作为返回值返回即可instantiateItem
3:PageAdapter只显示三张需要哦缓存的图片。如果滑动的图片超过了缓存的范围。就会调用者方法,将图片摧毁destroyItem
4:isViewFromObject来判断显示的是否是同一张图片
具体的可以参考:
http://www.it165.net/pro/html/201403/11289.html

先从不可轮转的ViewPager说起

本例采用图片的数据源是三张的图片源。
1.具体的代码块:

public class MyAdapter extends PagerAdapter {
        public MyAdapter(List<ImageView> list) {
            super();
            m_List = list;
        }

        /** * 获取滑动的控件的个数。。。。 * @return */
        @Override
        public int getCount()
        {
            //Log.i("TAG","数量 "+m_List.size());
           return m_List.size();
        }

        /** *当要缓存的图片可以进行的时候,会调用者方法进行图片的初始化,我们将要显示的View放入到ViewGroup中。 * 然后作为返回值返回即可 * @param container * @param position * @return */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(m_List.get(position % m_List.size()),0);
            Log.i("TAG","初始化 "+position);
            return m_List.get(position % m_List.size());
        }

        /** * PageAdapter只显示三张需要哦缓存的图片。如果滑动的图片超过了缓存的范围。就会调用者方法,将图片摧毁 * @param container * @param position * @param object */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {

            container.removeView(m_List.get(position % 
            Log.i("TAG","摧毁某一项目 "+position);
            //super.destroyItem(container, position, object);
        }

        @Override
        public int getItemPosition(Object object) {
            //Log.i("TAG","getItemPosition ");
            return super.getItemPosition(object);
        }

        /** * 来判断显示的是否是同一张图片 * @param view * @param object * @return */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            //Log.i("TAG","判断是否是同一张图片 "+view.toString() +" "+object.toString());

            return view == object;
        }
    }

2.日志的输出和分析:
ViewPager实现图片轮转_第1张图片
left–to–right :在刚启动程序的 时候,只会加载两张图片资源(ViewPager的最大的缓存数量时3张)在从左向右的滑动过程中,会先执行destroyItem方法,然后在执行instantiateItem方法。第一次滑动的时候,会执行instantiateItem方法,缓存第三张图片。当第二次滑动的时候,会先摧毁poistion为0的然后在缓存position为3的位置的资源。
right–to–left :这个时候会先执行instantiateItem方法,然后在执行destroyItem方法。上图可以清楚的看出两种方法的执行顺序。

ViewPager实现图片轮转_第2张图片
3.遇到的问题以及解决方案:
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:3378)
at android.view.ViewGroup.addView(ViewGroup.java:3249)
at android.support.v4.view.ViewPager.addView(ViewPager.java:1341)
at android.view.ViewGroup.addView(ViewGroup.java:3194)
at
在你instantiateItem方法中判断该ImageVIew是否存在父类。如果存在则remove。(以上的问题会出现在ImageViews的数量时2或者3的时候)

 @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if(m_List.size() != 2 &&  m_List.size() != 3)
            {
                if(container.getChildCount() == m_List.size());
                {
                    container.removeView(m_List.get(position % m_List.size()));
                }
            }
            if(m_List.size() == 2 || m_List.size() == 3)
            {
                if(m_List.get(position % m_List.size()).getParent()!= null)
                {
                    container.removeView(m_List.get(position % m_List.size()));
                }
            }
            container.addView(m_List.get(position % m_List.size()),0);
            Log.i("TAG","初始化 "+position);
            return m_List.get(position % m_List.size());
        }

2.真正的轮转的实现:

使用到的定时器:Timber.http://www.cnblogs.com/xzf158/archive/2009/09/04/1560042.html(参考文档)
1.自定义的PageAdapter:

public class MyViewPager extends ViewPager{
    private Timer timer;
    private Activity activity;
    private List<ImageView> mList;
    public MyViewPager(Context context) {
        super(context);
    }

    public MyViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public void startFlow(Activity context,List<ImageView> list,int duration)
    {
        mList = list;
        activity = context;
        startTime();
        this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_UP)
                {
                    startTime();
                }
                else
                {
                    stopTime();
                }
                return false;
            }
        });
    }

    public void setDotLinear(final LinearLayout parentLinear,int selected,int unselected)
    {
        for(int i=0;i<mList.size();i++)
        {
            ImageView imageView = new ImageView(activity);
            imageView.setBackgroundResource(R.drawable.dot_selector);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.width = 10;
            params.height = 10;
            params.leftMargin  = 9;
            imageView.setLayoutParams(params);
            parentLinear.addView(imageView);
        }
        this.setOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                for(int i=0;i<mList.size();i++)
                {
                    if((position % mList.size()) == i)
                    {
                        parentLinear.getChildAt(i).setSelected(true);
                    }
                    else
                    {
                        parentLinear.getChildAt(i).setSelected(false);
                    }

                }
            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void startTime()
    {
        timer = new Timer();
// new Fix
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        MyViewPager.this.setCurrentItem(MyViewPager.this.getCurrentItem() + 1);
                    }
                });
            }
        },50000,5000);
    }

    public void stopTime()
    {
        if(timer != null)
        {
            timer.cancel();
        }
    }
}

2.Activity的代码块:

public class PageAdapterActivity extends Activity {
    private MyViewPager viewPager;
    private List<ImageView> m_List ;
    private LinearLayout dot_linear;
    private int images[] = new int[]{R.drawable.image1,
        R.drawable.image2,R.drawable.image3,R.drawable.image4,R.drawable.image5};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pageadapter);
        viewPager = (MyViewPager)this.findViewById(R.id.view);
        dot_linear = (LinearLayout)this.findViewById(R.id.dot_linear);
        m_List = new ArrayList<>();
        for(int i=0;i<3;i++)
        {
            ImageView imageView = new ImageView(PageAdapterActivity.this);
            ViewPager.LayoutParams params = new ViewPager.LayoutParams();
            params.width = ViewPager.LayoutParams.FILL_PARENT;
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            imageView.setLayoutParams(params);
            imageView.setImageResource(images[i]);
            m_List.add(imageView);
            initPoint();
        }

        MyAdapter adapter = new MyAdapter(m_List);
        viewPager.setAdapter(adapter);
        viewPager.startFlow(PageAdapterActivity.this,m_List,500);
        viewPager.setDotLinear(dot_linear,R.drawable.carousel_dot,R.drawable.carousel_un_dot);
        MyScrolller scrolller = new MyScrolller(this);
        scrolller.setDuration(viewPager,5000);
// viewPager.setCurrentItem((m_List.size()) * 100);
    }

    private void initPoint()
    {

    }

    public class MyAdapter extends PagerAdapter {
        public MyAdapter(List<ImageView> list) {
            super();
            m_List = list;
        }

        /** * 获取滑动的控件的个数。。。。 * @return */
        @Override
        public int getCount()
        {
            //Log.i("TAG","数量 "+m_List.size());
            if(m_List.size() == 1)
            {
                return  1;
            }
            else
            {
                return Integer.MAX_VALUE;
            }

        }

        /** *当要缓存的图片可以进行的时候,会调用者方法进行图片的初始化,我们将要显示的View放入到ViewGroup中。 * 然后作为返回值返回即可 * @param container * @param position * @return */
        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            if(m_List.size() != 2 &&  m_List.size() != 3)
            {
                if(container.getChildCount() == m_List.size());
                {
                    container.removeView(m_List.get(position % m_List.size()));
                }
            }
            if(m_List.size() == 2 || m_List.size() == 3)
            {
                if(m_List.get(position % m_List.size()).getParent()!= null)
                {
                    container.removeView(m_List.get(position % m_List.size()));
                }
            }
            container.addView(m_List.get(position % m_List.size()),0);
            Log.i("TAG","初始化 "+position);
            return m_List.get(position % m_List.size());
        }

        /** * PageAdapter只显示三张需要哦缓存的图片。如果滑动的图片超过了缓存的范围。就会调用者方法,将图片摧毁 * @param container * @param position * @param object */
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if(m_List.size() != 2 &&  m_List.size() != 3)
            {
                container.removeView(m_List.get(position % m_List.size()));
            }
            Log.i("TAG","摧毁某一项目 "+position);
            //super.destroyItem(container, position, object);
        }

        @Override
        public int getItemPosition(Object object) {
            //Log.i("TAG","getItemPosition ");
            return super.getItemPosition(object);
        }

        /** * 来判断显示的是否是同一张图片 * @param view * @param object * @return */
        @Override
        public boolean isViewFromObject(View view, Object object) {
            //Log.i("TAG","判断是否是同一张图片 "+view.toString() +" "+object.toString());

            return view == object;
        }
    }

    public class MyScrolller extends Scroller {
        private Context context;
        private int mDuration;
        public MyScrolller(Context context) {
            super(context);
            this.context = context;
        }

        public MyScrolller(Context context, Interpolator interpolator, boolean flywheel) {
            super(context, interpolator, flywheel);
            this.context = context;
        }

        public MyScrolller(Context context, Interpolator interpolator)
        {
            super(context, interpolator);
            this.context = context;
        }

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

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

        public void setDuration(ViewPager pager,int duration)
        {
            try {
                Field field = ViewPager.class.getDeclaredField("mScroller");
                field.setAccessible(true);
                this.setmDuration(duration);
                field.set(pager,duration);
            }catch (Exception e)
            {
                e.printStackTrace();
            }
        }

        public int getmDuration() {
            return mDuration;
        }

        public void setmDuration(int mDuration) {
            this.mDuration = mDuration;
        }
    }
}

你可能感兴趣的:(viewpager,图片)