viewpager實現自動循環輪播圖

本文實例為大傢分享瞭viewpager自動循環輪播圖的具體代碼,供大傢參考,具體內容如下

佈局文件

android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content">
  <androidx.viewpager.widget.ViewPager
   android:id="@+id/vp_adv"
   android:layout_width="match_parent"
   android:layout_height="160dp"/>
<LinearLayout
   android:id="@+id/View_indicator"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:layout_below="@id/vp_adv"
   android:layout_marginTop="-25dp"
   android:orientation="horizontal"
   android:gravity="right">
  </LinearLayout>
 </RelativeLayout>
</LinearLayout>

核心代碼

public class MainActivity extends AppCompatActivity {
 private ImageView indicator;//表示圓點指示器
 private ImageView [] indicators;//保存圓點指示器的數組
 private boolean iscontinue = true;
 private ViewPager viewPager;
 private ViewGroup viewGroup;
 private ArrayList<Fragment> fragments;
 List<Integer> 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<View> 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;i++){
   indicator = new ImageView(this);
   indicator.setLayoutParams(new LinearLayout.LayoutParams(40,40));
   indicator.setPadding(5,5,5,5);
   indicators[i] = indicator;
   if(i == 0){
    indicators[i].setBackgroundResource(R.drawable.ic_launcher_background);
   }else{
    indicators[i].setBackgroundResource(R.drawable.ic_launcher_foreground);
   }
   viewGroup.addView(indicators[i]);
  }
  //設置ViewPager適配器
  viewPager.setAdapter(new pagerAdapter(getSupportFragmentManager()));

  //設置viewPager監聽器
  viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
   @Override
   public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

   }

   @Override
   public void onPageSelected(int position) {
    index.getAndSet(position);
    for(int i = 0;i <indicators.length; i ++){
     if(i ==position){
      indicators[i].setBackgroundResource(R.drawable.a1);
     }else{
      indicators[i].setBackgroundResource(R.drawable.a2);
     }
    }

   }

   @Override
   public void onPageScrollStateChanged(int state) {

   }
  });
  viewPager.setOnTouchListener(new View.OnTouchListener() {
   @Override
   public boolean onTouch(View view, MotionEvent motionEvent) {
    switch (motionEvent.getAction()){
     case MotionEvent.ACTION_DOWN:
      iscontinue = false;
      break;
     case MotionEvent.ACTION_UP:
      iscontinue = true;
      break;
    }
    return false;
   }
  });
  //使用多線程切換UI
  new Thread(new Runnable() {
   @Override
   public void run() {
    while (true){
     if(iscontinue){
      viewHandler.sendEmptyMessage(index.get());
      whatOption();
     }
    }

   }
  }).start();
 }
 private void whatOption(){
  index.incrementAndGet();//將當前位置+1;
  if(index.get()>indicators.length-1){
   index.getAndAdd(-4);
  }
  try {
   Thread.sleep(2000);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
 }
 private void initFragments() {
  imgs = new ArrayList<Integer>();
  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<View> viewList;
 public MyPagerAdapter(List<View>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));
 }
}

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。

推薦閱讀: