ViewPaper圖片輪播是挺經常使用的一個東西java
處理很差 可能常常遇到崩潰啥的問題,經一位大神指導,總結出一個類android
首先自定義一個ViewPaper,能夠當作一個工具類用ide
public class MyViewpaper extends ViewPager { private Handler mHandler ; public MyViewpaper(Context context){ super(context); mHandler = new AutoHandler(this); } public MyViewpaper(Context context, AttributeSet attrs) { super(context, attrs); mHandler = new AutoHandler(this); } public class AutoHandler extends Handler { public static final int SCROOL_ONECE = 1; private SoftReference<MyViewpaper> mvpSoftReference; public AutoHandler(MyViewpaper viewpaper){ mvpSoftReference = new SoftReference<MyViewpaper>(viewpaper); } @Override public void handleMessage(Message msg) { super.handleMessage(msg); MyViewpaper viewpaper = mvpSoftReference.get(); if(viewpaper !=null){ if(SCROOL_ONECE == msg.what){ mHandler.removeMessages(AutoHandler.SCROOL_ONECE); viewpaper.scrollOnece(); } } } } public void scrollOnece(){ PagerAdapter adapter = getAdapter(); int currentItem = getCurrentItem(); int totalCount =0; //有一張不自動滑動 if(adapter == null||(totalCount = adapter.getCount())<=1){ return; } int nextItem = currentItem +1; if(totalCount-1 == currentItem){ nextItem = 0; setCurrentItem(nextItem,false); }else{ setCurrentItem(nextItem,true); } mHandler.sendEmptyMessageDelayed(AutoHandler.SCROOL_ONECE, 5000); } public void startAutoScroll(long dayTime){ PagerAdapter adapter = getAdapter(); int totalCount =0; //有一張不自動滑動 if(adapter == null||(totalCount = adapter.getCount())==0){ return; } //解決內存被回收的時候再次顯示處理 int currentItem = getCurrentItem(); setCurrentItem(currentItem,false); mHandler.sendEmptyMessageDelayed(AutoHandler.SCROOL_ONECE, dayTime); } }
xml中定義工具
<com.iningke.qizhong.base.MyViewpaper android:id="@+id/viewpager_lunbo" android:layout_width="match_parent" android:layout_height="match_parent"/>
而後就是調用this
myViewpaper.startAutoScroll(5000);
5000指的是圖片滾動到下一張圖片的時間code