码迷,mamicode.com
首页 > 移动开发 > 详细

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

时间:2015-07-06 14:22:19      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:

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

 

技术分享

 

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

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

标签:

原文地址:http://my.oschina.net/hejunbinlan/blog/475141

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!