Android ViewPager真正的实现无限循环滚动

Android ViewPager真正的实现无限循环滚动

在存放View的集合中的第一个位置放入真正的最后一个View,而在最后一个放入第一个。具体请参照下图以及代码!

Android ViewPager真正的实现无限循环滚动

  1. package com.xinye.ui;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import net.tsz.afinal.FinalBitmap;
  5. import net.tsz.afinal.FinalHttp;
  6. import net.tsz.afinal.http.AjaxCallBack;
  7. import org.json.JSONArray;
  8. import org.json.JSONException;
  9. import org.json.JSONObject;
  10. import android.graphics.Color;
  11. import android.support.v4.view.PagerAdapter;
  12. import android.support.v4.view.ViewPager;
  13. import android.support.v4.view.ViewPager.OnPageChangeListener;
  14. import android.util.Log;
  15. import android.view.LayoutInflater;
  16. import android.view.View;
  17. import android.view.ViewGroup;
  18. import android.widget.ImageView;
  19. import android.widget.ImageView.ScaleType;
  20. import android.widget.TextView;
  21. import android.widget.Toast;
  22. import com.xinye.R;
  23. import com.xinye.domain.Bargain;
  24. import com.xinye.domain.Screen;
  25. import com.xinye.domain.ViewFrame;
  26. import com.xinye.util.ApplicationUtils;
  27. import com.xinye.util.ConstantsUtils;
  28. import com.xinye.util.FileUtils;
  29. import com.xinye.util.ImagePathUtils;
  30. import com.xinye.util.LogUtils;
  31. import com.xinye.util.StringUtils;
  32. import com.xinye.view.SlidingView;
  33. /**
  34. * Fragment
  35. *
  36. *
  37. *
  38. */
  39. public class BannerFragment extends BaseFragment implements OnPageChangeListener {
  40.    // 当前Fragment的RootView
  41.    private View mRootView = null;
  42.    // 当前Fragment中的ViewPager
  43.    private ViewPager mViewPager = null;
  44.    // 展示当前页面标识的TextView
  45.    private TextView mTextView = null;
  46.    // 布局填充器对象
  47.    private LayoutInflater mLayoutInflater = null;
  48.    // 保存Bargain信息的ArrayList
  49.    private ArrayList<Bargain> mBargainList = new ArrayList<Bargain>();
  50.    // 保存所有的ViewPager的View
  51.    private ArrayList<ImageView> mViewList = new ArrayList<ImageView>();
  52.    // Bitmap载入工具类
  53.    private FinalBitmap mFinalBitmap;
  54.    // 切换到左边的ImageView
  55.    private ImageView mToLeftImageView = null;
  56.    // 切换到右侧的ImageView
  57.    private ImageView mToRightImageView = null;
  58.    // 图片URL列表
  59.    private static ArrayList<String> mImageUrlList = new ArrayList<String>();
  60.    @Override
  61.    protected void initContent() {
  62.       mFinalBitmap = FinalBitmap.create(mActivity, FileUtils.getCacheDirectory(mActivity));
  63.       mTopbarTextView.setText(R.string.popup_banner);
  64.       mPopupBannerTextView.setTextColor(Color.argb(0xff, 0xa1, 0x01, 0x01));
  65.       mTopbarLeftImageView.setImageResource(R.drawable.topbar_banner);
  66.       mLayoutInflater = mActivity.getLayoutInflater();
  67.       mRootView = mLayoutInflater.inflate(R.layout.fragment_banner, null);
  68.       mbaseLinearLayout.addView(mRootView);
  69.       mViewPager = (ViewPager) mRootView.findViewById(R.id.bannerFragmentViewPager);
  70.       mTextView = (TextView) mRootView.findViewById(R.id.countBannerFragmentTextView);
  71.       mToLeftImageView = (ImageView) mRootView.findViewById(R.id.toLeftBannerFragmentImageView);
  72.       mToLeftImageView.setOnClickListener(BannerFragment.this);
  73.       mToRightImageView = (ImageView) mRootView.findViewById(R.id.toRightBannerFragmentImageView);
  74.       mToRightImageView.setOnClickListener(BannerFragment.this);
  75.       try {
  76.          if(mImageUrlList != null && mImageUrlList.size() > 0){
  77.             initViewPager();
  78.          }else{
  79.             initData();
  80.          }
  81.       } catch (Exception e) {
  82.          e.printStackTrace();
  83.       }
  84.    }
  85.    // 初始化数据
  86.    private void initData() throws Exception {
  87.       HashMap<String, Object> data = new HashMap<String, Object>();
  88.       data.put("loginUserId", UserLoginActivity.userID);
  89.       data.put("checkStr", UserLoginActivity.token);
  90.       data.put("isMember", UserLoginActivity.isMember);
  91.       String url = StringUtils.composeUrl(ConstantsUtils.BANNER_LIST_URL, data);
  92.       LogUtils.printLog(Log.INFO, LogUtils.LOG_TAG, "BannerFragment initData url = " + url);
  93.       new FinalHttp().get(url, new AjaxCallBack<String>() {
  94.          @Override
  95.          public void onSuccess(String t) {
  96.             LogUtils.printLog(Log.INFO, LogUtils.LOG_TAG, "banner list JSON:" + t);
  97.             parseJSON(t);
  98.             super.onSuccess(t);
  99.          }
  100.          @Override
  101.          public void onFailure(Throwable t, String strMsg) {
  102.             if(t != null){
  103.                mImageUrlList = FileUtils.readListFromFile(mActivity, FileUtils.LIST_BANNER_FILE_NAME);
  104.                if(mImageUrlList != null){
  105.                   initViewPager();
  106.                }
  107.             }
  108.             super.onFailure(t, strMsg);
  109.          }
  110.       });
  111.    }
  112.    // 解析JSON
  113.    private void parseJSON(String t) {
  114.       if (t == null) {
  115.          return;
  116.       }
  117.       try {
  118.          JSONObject tObj = new JSONObject(t);
  119.          int status = tObj.getInt("status");
  120. // String message = tObj.getString("message");
  121.          if (status == 0) {
  122.             String dataString = tObj.getString("data");
  123.             if (dataString != null && !dataString.equalsIgnoreCase("null")) {
  124.                JSONObject dataObj = new JSONObject(dataString);
  125.                String partnerBargainFormListString = dataObj.getString("partnerBargainFormList");
  126.                if (partnerBargainFormListString != null && !partnerBargainFormListString.equalsIgnoreCase("null")) {
  127.                   JSONArray array = new JSONArray(partnerBargainFormListString);
  128.                   Screen screen = ApplicationUtils.getScreen(mActivity);
  129.                   if (array != null) {
  130.                      int len = array.length();
  131.                      for (int i = 0; i < len; i++) {
  132.                         JSONObject obj = array.getJSONObject(i);
  133.                         String bargainString = obj.getString("partnerBargain");
  134.                         Bargain bargain = new Bargain();
  135.                         if (bargainString != null && !bargainString.equalsIgnoreCase("null")) {
  136.                            JSONObject bargainObj = new JSONObject(bargainString);
  137.                            bargain.partnerCategoryId = bargainObj.getLong("partnerCategoryId");
  138.                            bargain.partnerId = bargainObj.getLong("partnerId");
  139.                            bargain.pictureId = bargainObj.getLong("pictureId");
  140.                            bargain.title = bargainObj.getString("title");
  141.                            bargain.displayOrder = bargainObj.getLong("displayOrder");
  142.                            bargain.dailySpecialsId = bargainObj.getLong("dailySpecialsId");
  143.                            bargain.bargainId = bargainObj.getLong("bargainId");
  144.                         }
  145.                         String pic = obj.getString("pic");
  146.                         pic = ImagePathUtils.getBannerRealPath(pic,screen);
  147.                         bargain.pic = pic;
  148.                         mBargainList.add(bargain);
  149.                         mImageUrlList.add(bargain.pic);
  150.                      }
  151.                      FileUtils.writeListToFile(mActivity, FileUtils.LIST_BANNER_FILE_NAME, mImageUrlList);
  152.                      initViewPager();
  153.                   }
  154.                } else {
  155.                   return;
  156.                }
  157.             } else {
  158.                return;
  159.             }
  160.          }
  161.       } catch (JSONException e) {
  162.          e.printStackTrace();
  163.       }
  164.    }
  165.    // 初始化ViewPager
  166.    private void initViewPager() {
  167.       if(!(mImageUrlList != null && mImageUrlList.size() > 0)){
  168.          return;
  169.       }
  170.       int length = mImageUrlList.size() + 2;
  171.       for (int i = 0; i < length; i++) {
  172.          ImageView mViewPagerImageView = new ImageView(mActivity);
  173.          ViewGroup.LayoutParams viewPagerImageViewParams =
  174.                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
  175.                      ViewGroup.LayoutParams.FILL_PARENT);
  176.          mViewPagerImageView.setLayoutParams(viewPagerImageViewParams);
  177.          mViewPagerImageView.setScaleType(ScaleType.FIT_XY);
  178.          mViewPagerImageView.setOnClickListener(BannerFragment.this);
  179.          mViewList.add(mViewPagerImageView);
  180.       }
  181.       if (mViewList != null && mViewList.size() > 0) {
  182.          mViewPager.setAdapter(new ViewpagerAdapter());
  183.       }
  184.       mViewPager.setOnPageChangeListener(BannerFragment.this);
  185.       if (mImageUrlList.size() == 0) {
  186.          mTextView.setText(String.format("0 / %s", mImageUrlList.size()));
  187.       } else {
  188.          mTextView.setText(String.format("1 / %s", mImageUrlList.size()));
  189.       }
  190.       mViewPager.setCurrentItem(1);
  191.       if (mActivity.getSlidingMenu() != null && mActivity.getSlidingMenu().getSlidingView() != null) {
  192.          SlidingView sv = mActivity.getSlidingMenu().getSlidingView();
  193.          sv.setOnInterceptListener(new SlidingView.OnInterceptListener() {
  194.             @Override
  195.             public ViewFrame getInterceptViewFrame() {
  196.                ViewFrame frame = new ViewFrame(0, 50, mViewPager.getWidth(), mViewPager.getHeight());
  197.                return frame;
  198.             }
  199.          });
  200.       }
  201.    }
  202.    @Override
  203.    protected void init() {
  204.    }
  205.    /**
  206.     * PagerAdapter
  207.     * @author
  208.     *
  209.     */
  210.    class ViewpagerAdapter extends PagerAdapter {
  211.       @Override
  212.       public void destroyItem(View container, int position, Object object) {
  213.          ImageView view = mViewList.get(position % mViewList.size());
  214.          ((ViewPager) container).removeView(view);
  215.          view.setImageBitmap(null);
  216.       }
  217.       @Override
  218.       public Object instantiateItem(View container, int position) {
  219.          ((ViewPager) container).addView(mViewList.get(position));
  220.             return mViewList.get(position);
  221.       }
  222.       @Override
  223.       public int getCount() {
  224.          return mViewList.size();
  225.       }
  226.       @Override
  227.       public boolean isViewFromObject(View view, Object object) {
  228.          return view == object;
  229.       }
  230.    }
  231.    @Override
  232.    public void onPageScrollStateChanged(int state) {
  233.    }
  234.    @Override
  235.    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
  236.    }
  237.    @Override
  238.    public void onPageSelected(int position) {
  239.       if(position == 0){
  240.          mFinalBitmap.display(mViewList.get(position), mImageUrlList.get(mImageUrlList.size() - 1));
  241.       }else if(position == mViewList.size() - 1){
  242.          mFinalBitmap.display(mViewList.get(position), mImageUrlList.get(0));
  243.       }else{
  244.          mFinalBitmap.display(mViewList.get(position), mImageUrlList.get(position - 1));
  245.       }
  246.       int pageIndex = position;
  247.        if(position == 0){
  248.           pageIndex = mImageUrlList.size();
  249.        }else if(position == mImageUrlList.size() + 1){
  250.           pageIndex = 1;
  251.        }
  252.        if(position != pageIndex){
  253.           mViewPager.setCurrentItem(pageIndex, false);
  254.           return;
  255.        }
  256.        int count = mViewList.size() - 2;
  257.        if(mViewList != null && count > 0){
  258.           int index = (position);
  259.           String text = index + "/" + count;
  260.           mTextView.setText(text);
  261.        }else{
  262.          String text = 0 + " / " + 0;
  263.          mTextView.setText(text);
  264.        }
  265.    }
  266.    @Override
  267.    public void onClick(View v) {
  268.       switch (v.getId()) {
  269.       // 切换到左边的ImageView
  270.       case R.id.toLeftBannerFragmentImageView: {
  271.          if (mViewPager != null && mViewPager.getCurrentItem() > 0) {
  272.             mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1, true);
  273.          } else {
  274.             Toast.makeText(mActivity, R.string.banner_is_first, Toast.LENGTH_SHORT).show();
  275.          }
  276.       }
  277.          break;
  278.       // 切换到右边的ImageView
  279.       case R.id.toRightBannerFragmentImageView: {
  280.          if (mViewPager != null && mViewList != null && mViewPager.getCurrentItem() < Integer.MAX_VALUE - 1) {
  281.             mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1, true);
  282.          } else {
  283.             Toast.makeText(mActivity, R.string.banner_is_last, Toast.LENGTH_SHORT).show();
  284.          }
  285.       }
  286.          break;
  287.       }
  288.       super.onClick(v);
  289.    }
  290.    @Override
  291.    public void onPause() {
  292.       if (mFinalBitmap != null) {
  293.          mFinalBitmap.onPause();
  294.       }
  295.       super.onPause();
  296.    }
  297.    @Override
  298.    public void onResume() {
  299.       if (mFinalBitmap != null) {
  300.          mFinalBitmap.onResume();
  301.       }
  302.       super.onResume();
  303.    }
  304.    @Override
  305.    public void onDestroy() {
  306.       if (mFinalBitmap != null) {
  307.          mFinalBitmap.onDestroy();
  308.       }
  309.       super.onDestroy();
  310.    }
  311. }

你可能感兴趣的:(Android ViewPager真正的实现无限循环滚动)