viewpager实现自动循环轮播图
本文实例为大家分享了viewpager自动循环轮播图的具体代码,供大家参考,具体内容如下
布局文件
android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity">
核心代码
publicclassMainActivityextendsAppCompatActivity{ privateImageViewindicator;//表示圆点指示器 privateImageView[]indicators;//保存圆点指示器的数组 privatebooleaniscontinue=true; privateViewPagerviewPager; privateViewGroupviewGroup; privateArrayListfragments; List imgs=null; privateAtomicIntegerindex=newAtomicInteger(); privateHandlerviewHandler=newHandler(){ @Override publicvoidhandleMessage(@NonNullMessagemsg){ super.handleMessage(msg); viewPager.setCurrentItem(msg.what); } }; @Override protectedvoidonCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } publicvoidinitView(){ viewPager=findViewById(R.id.vp_adv); viewGroup=findViewById(R.id.View_indicator); //四张广告图片加载到集合中进行保存 List listPics=newArrayList<>(); ImageViewimg1=newImageView(this); img1.setBackgroundResource(R.mipmap.food1); listPics.add(img1); ImageViewimg2=newImageView(this); img1.setBackgroundResource(R.mipmap.shop2); listPics.add(img2); ImageViewimg3=newImageView(this); img1.setBackgroundResource(R.mipmap.shop3); listPics.add(img3); ImageViewimg4=newImageView(this); img1.setBackgroundResource(R.mipmap.shop4); listPics.add(img4); initFragments(); //动态设置四个圆点属性 indicators=newImageView[listPics.size()]; for(inti=0;i indicators.length-1){ index.getAndAdd(-4); } try{ Thread.sleep(2000); }catch(InterruptedExceptione){ e.printStackTrace(); } } privatevoidinitFragments(){ imgs=newArrayList (); imgs.add(R.mipmap.timg1); imgs.add(R.mipmap.timg2); imgs.add(R.mipmap.timg3); imgs.add(R.mipmap.timg4); } classpagerAdapterextendsFragmentPagerAdapter{ publicpagerAdapter(FragmentManagerfm){ super(fm); } @Override publicFragmentgetItem(intarg0){ //得到要显示的对象并初始化图片 MyFragmentfm=newMyFragment(); fm.setUrl(imgs.get(arg0)); returnfm; } @Override publicintgetCount(){ returnimgs.size(); } } } classMyPagerAdapterextendsPagerAdapter{ privateList viewList; publicMyPagerAdapter(List viewList){ this.viewList=viewList; } @Override publicintgetCount(){ returnviewList.size(); } @Override publicbooleanisViewFromObject(@NonNullViewview,@NonNullObjectobject){ returnview==object; } @NonNull @Override publicObjectinstantiateItem(@NonNullViewGroupcontainer,intposition){ container.addView(viewList.get(position)); returnviewList.get(position); } @Override publicvoiddestroyItem(@NonNullViewGroupcontainer,intposition,@NonNullObjectobject){ container.removeView(viewList.get(position)); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。