本文实例为大家分享了viewpager自动循环轮播图的具体代码,供大家参考,具体内容如下
布局文件
android:layout_ android:layout_ tools:cOntext=".MainActivity">
核心代码
public class MainActivity extends AppCompatActivity { private ImageView indicator;//表示圆点指示器 private ImageView [] indicators;//保存圆点指示器的数组 private boolean iscOntinue= true; private ViewPager viewPager; private ViewGroup viewGroup; private ArrayListfragments; List imgs = null; private AtomicInteger index = new AtomicInteger(); private Handler viewHandler= new Handler(){ @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); viewPager.setCurrentItem(msg.what); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); } public void initView(){ viewPager=findViewById(R.id.vp_adv); viewGroup=findViewById(R.id.View_indicator); //四张广告图片加载到集合中进行保存 List listPics = new ArrayList<>(); ImageView img1 = new ImageView(this); img1.setBackgroundResource(R.mipmap.food1); listPics.add(img1); ImageView img2 = new ImageView(this); img1.setBackgroundResource(R.mipmap.shop2); listPics.add(img2); ImageView img3 = new ImageView(this); img1.setBackgroundResource(R.mipmap.shop3); listPics.add(img3); ImageView img4 = new ImageView(this); img1.setBackgroundResource(R.mipmap.shop4); listPics.add(img4); initFragments(); //动态设置四个圆点属性 indicators = new ImageView[listPics.size()]; for(int i=0;i indicators.length-1){ index.getAndAdd(-4); } try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } } private void initFragments() { imgs = new ArrayList (); imgs.add(R.mipmap.timg1); imgs.add(R.mipmap.timg2); imgs.add(R.mipmap.timg3); imgs.add(R.mipmap.timg4); } class pagerAdapter extends FragmentPagerAdapter{ public pagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int arg0) { //得到要显示的对象并初始化图片 MyFragment fm = new MyFragment(); fm.setUrl(imgs.get(arg0)); return fm; } @Override public int getCount() { return imgs.size(); } } } class MyPagerAdapter extends PagerAdapter{ private List viewList; public MyPagerAdapter(List viewList){ this.viewList = viewList; } @Override public int getCount() { return viewList.size(); } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view==object; } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { container.addView(viewList.get(position)); return viewList.get(position); } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView(viewList.get(position)); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。