第一步 初始化viewpager
//初始化bannerprivate void initBannerView(View v) { vpBanner = new ArrayList<ImageView>(); for (int i = 0; i < bannerResource.length; i++) { ImageView iv = new ImageView(getActivity()); iv.setImageResource(bannerResource[i]); vpBanner.add(iv); } vp = (ViewPager) v.findViewById(R.id.vp_banner); vp.setAdapter(new BannerAdapter());} 第二步 初始化 填充数据
//填充bannerclass BannerAdapter extends PagerAdapter { @Override public boolean isViewFromObject(View view, Object o) { return view == o; } @Override public int getCount() { return vpBanner.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { ImageView iv = vpBanner.get(position); container.addView(iv); return iv; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); }}第四步 去设置每秒切换图片 并提交给UI更新
@Overridepublic void onStart() { super.onStart(); scheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); //每隔3秒钟切换一张图片 scheduledExecutorService.scheduleWithFixedDelay(new ViewPagerTask(), 3, 3, TimeUnit.SECONDS); } //切换图片private class ViewPagerTask implements Runnable { @Override public void run() { // TODO Auto-generated method stub currentItem = (currentItem + 1) % bannerResource.length; //更新界面 // handler.sendEmptyMessage(0); handler.obtainMessage().sendToTarget(); } } private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { // TODO Auto-generated method stub //设置当前页面mViewPager.setCurrentItem(currentItem); //Log.d("msg", vp.getCurrentItem() + ""); vp.setCurrentItem(currentItem); }};
时间: 2024-10-18 13:31:07