[view] 04_ViewPager-页面切换,定时页面切换

Android 4.0

ViewPager
页面切换,定时页面切换

技术点:
1、使用第三方UI类,只需要将完整包名加入就行
2、Timer和ScheduledExecutorService
3、Handler+Message或者runOnUiThread(runnable)更新界面ui
4、ViewPager的适配器类
步骤:
1、布局
2、将要显示的图片,文字分别用int和String数组存起来
3、然后将布局中的显示的ImageView和显示的状态点分别存到一个ArrayList中去
4、设置viewpager的变化事件
5、在变化页面 onPageSelected中,将对应的文本标题和状态的点显示正确

定时切换页面
a)使用ScheduledExecutorService而不是Timer,
b)定时的切换,使用handler+Message更新界面
在Activity可见(onStart)时,开启定时,不可见时(onStop)时,关闭定时
可见时,将当前的item页面也增加1
@Override
protected void onStart() {
    super.onStart();
    scheduledExecutorService = Executors.newScheduledThreadPool(imageIds.length);
    Runnable command = new Runnable() {
        
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 将当前页面增加1,然后取余,为了保证最后一页可以循环到第一页page
                    currentItem = (currentItem + 1) % imageIds.length;
                    viewPager.setCurrentItem(currentItem);
                }
            });
        }
    };
    scheduledExecutorService.scheduleWithFixedDelay(command , 2, 2, TimeUnit.SECONDS);
}
@Override
protected void onStop() {
    super.onStop();
    if (scheduledExecutorService != null) {
        scheduledExecutorService.shutdown();
    }
}
核心代码:
package cn.zengfansheng.viewpager;
 
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
 
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
 
public class MainActivity extends Activity {
 
    private int imageIds[];
    private String descs[];
 
    private List<ImageView> images;
    private List<View> dots;
 
    private ViewPager viewPager;
    private PagerAdapter pagerAdapter;
 
    private TextView tv_desc;// 图片描述
 
    private int oldPosition = 0;// 记录切换页面前一个页面的位置
    private int currentItem;// 当前page的位置
 
    private ScheduledExecutorService scheduledExecutorService;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // 1、图片资源id数组
        imageIds = new int[] {
            R.drawable.a,
            R.drawable.b,
            R.drawable.c,
            R.drawable.d,
            R.drawable.e
        };
 
        // 2、图片描述数组
        descs = new String[] {
            "巩俐不低俗,我就不能低俗",   
            "扑树又回来啦!再唱经典老歌引万人大合唱",   
            "揭秘北京电影如何升级",   
            "乐视网TV版大派送",   
            "热血屌丝的反杀"
        };
 
        // 3、要显示的ImageView集合
        images = new ArrayList<ImageView>();
        for (int imageId : imageIds) {
            ImageView iv = new ImageView(this);
            iv.setImageResource(imageId);
            images.add(iv);
        }
        // 4、要显示的状态点dot集合
        dots = new ArrayList<View>();
        dots.add(this.findViewById(R.id.dt1));
        dots.add(this.findViewById(R.id.dt2));
        dots.add(this.findViewById(R.id.dt3));
        dots.add(this.findViewById(R.id.dt4));
        dots.add(this.findViewById(R.id.dt5));
 
        // 初始化数据完毕----------------------
 
        tv_desc = (TextView) this.findViewById(R.id.tv_desc);
        tv_desc.setText(descs[0]);
 
        viewPager = (ViewPager) this.findViewById(R.id.view_pager);
        pagerAdapter = new MyPagerAdapter();
        viewPager.setAdapter(pagerAdapter);
        // viewPager.setCurrentItem(oldPosition);//设置当前显示的item
 
        // 设置viewPager的page改变事件
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {
 
            // 另外一张page被完全展示的时候,调用,参数代表当前page的位置,从0开始
            @Override
            public void onPageSelected(int position) {
                // System.out.println("onPageSelected:" + i);
 
                // 文字title改变
                tv_desc.setText(descs[position]);
 
                // 点dot改变,前一个位置变成normal,当前变成enabled
                dots.get(oldPosition).setBackgroundResource(R.drawable.dot_normal);
                dots.get(position).setBackgroundResource(R.drawable.dot_enable);
 
                // 更新上一个位置为当前位置
                oldPosition = position;
                currentItem = position;
            }
 
            // page在拖动的过程中,调用该方法
            @Override
            public void onPageScrolled(int i, float f, int j) {
                // System.out.println("onPageScrolled:");
            }
 
            // 只要状态一变化就调用,page滚动开始和结束时会调用,状态变化:1-2-0
            @Override
            public void onPageScrollStateChanged(int i) {
                // System.out.println("onPageScrollStateChanged:" + i);
            }
        });
    }
 
    //pageadapter
    private class MyPagerAdapter extends PagerAdapter {
 
        /**
         * viewpager的长度
         */

        @Override
        public int getCount() {
            return imageIds.length;
        }
 
        // 判断是同一个view
        /**
         * 判断滑动的控件和将要显示的控件是否为同一个 true 直接复用 false 会调用instantiateItem() 得到一个新的对象
         */

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }
 
        /**
         * 移除ImageView对象
         */

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            // super.destroyItem(container, position, object);//这个要注释掉
 
            // View view = container.getChildAt(position);
            // container.removeView(view);
 
            // container.removeViewAt(position);
 
            container.removeView(images.get(position));
        }
 
        /**
         * 得到一个Object对象就是ImageView
         */

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(images.get(position));
            return images.get(position);
        }
    }
 
    @Override
    protected void onStart() {
        super.onStart();
        scheduledExecutorService = Executors.newScheduledThreadPool(imageIds.length);
        Runnable command = new Runnable() {
 
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
 
                    @Override
                    public void run() {
                        // 将当前页面增加1,然后取余,为了保证最后一页可以循环到第一页page
                        currentItem = (currentItem + 1) % imageIds.length;
                        viewPager.setCurrentItem(currentItem);
                    }
                });
            }
        };
        scheduledExecutorService.scheduleWithFixedDelay(command , 2, 2, TimeUnit.SECONDS);
    }
 
    @Override
    protected void onStop() {
        super.onStop();
        if (scheduledExecutorService != null) {
            scheduledExecutorService.shutdown();
        }
    }
}
结果:





12-01 16:11:29.922: E/AndroidRuntime(2966):     at cn.zengfansheng.viewpager.MainActivity$MyPagerAdapter.destroyItem(MainActivity.java:84)