Viewpager 自动轮播(无限循环) ,手动滑动时停止轮播+底部小圆点(二)

项目结构如下:

Viewpager 自动轮播(无限循环) ,手动滑动时停止轮播+底部小圆点(二)_第1张图片


Volley工具类:

VolleyTool类负责实例化mRequestQueue和mImageLoader。

package com.example.utils;

import android.content.Context;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;

public class VolleyTool {
	private static VolleyTool mInstance = null;
	private RequestQueue mRequestQueue;
	private ImageLoader mImageLoader;
	
	private VolleyTool(Context context){
		mRequestQueue = Volley.newRequestQueue(context);
		mImageLoader = ImageLoaderUtils.getImageLoader(mRequestQueue);
	}
	
	public static VolleyTool getInstance(Context context){
		if (mInstance==null) {
			mInstance = new VolleyTool(context);
		}
		return mInstance;
	}

	public RequestQueue getmRequestQueue() {
		return mRequestQueue;
	}

	public ImageLoader getmImageLoader() {
		return mImageLoader;
	}

	public void release() {
		this.mImageLoader = null;
		this.mRequestQueue = null;
		mInstance = null;
	}

}
JsonUtils 是解析json数据的工具类

package com.example.utils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;

public class JsonUtils {

	/**
	 * 解析json数据的工具类
	 * 
	 * @param context
	 * @param json_path
	 * @param callBack
	 * @param queue
	 */
	public static void parseJsonString(Context context, String json_path,
			final JsonStringCallBack callBack,
			final RequestTimeOutCallBack timeOutCallBack, RequestQueue queue) {
		StringRequest request = new StringRequest(json_path,
				new Listener() {
					@Override
					public void onResponse(String response) {
						// TODO Auto-generated method stub
						callBack.jsonStringCallBack(response);
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						timeOutCallBack.timeOutCallBack(error.getMessage());
					}
				}) {
			@Override
			protected Response parseNetworkResponse(
					NetworkResponse response) {
				String str = null;
				try {
					str = new String(response.data, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return Response.success(str,
						HttpHeaderParser.parseCacheHeaders(response));
			}
		};

		request.setRetryPolicy(new DefaultRetryPolicy(4000,
				DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
				DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

		// 添加到队列中
		queue.add(request);
	}

	/**
	 * 解析数组开始的json字符串
	 * 
	 * @param context
	 * @param json_path
	 * @param callBack
	 * @param queue
	 */
	public static void parseJsonArray(Context context, String json_path,
			final JsonArrayCallBack callBack, RequestQueue queue) {
		JsonArrayRequest request = new JsonArrayRequest(json_path,
				new Listener() {
					@Override
					public void onResponse(JSONArray response) {
						// TODO Auto-generated method stub
						callBack.jsonArrayCallBack(response);
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// TODO Auto-generated method stub
						Log.i("TAG", error.getMessage());
					}
				});
		// 添加到队列中
		queue.add(request);
	}

	/**
	 * 
	 * @param context
	 * @param json_path
	 * @param callBack
	 */
	public static void parseJsonObject(Context context, String json_path,
			final Map map, final JsonObjectCallBack callBack,
			RequestQueue queue) {
		JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
				Request.Method.POST, json_path, null,
				new Response.Listener() {
					@Override
					public void onResponse(JSONObject response) {
						// TODO Auto-generated method stub
						// System.out.println("----->>response=" + response);
						callBack.jsonObjectCallBack(response);
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// TODO Auto-generated method stub

					}

				})

		{
			@Override
			protected Map getParams() throws AuthFailureError {
				return map;
			}

			@Override
			public Map getHeaders() throws AuthFailureError {
				HashMap headers = new HashMap();
				headers.put("Accept", "application/json");
				headers.put("Content-Type", "application/json; charset=UTF-8");
				return headers;

			}
		};
		queue.add(jsonObjectRequest);
	}

	// 解析json对象的回调接口
	public interface JsonObjectCallBack {
		public void jsonObjectCallBack(JSONObject jsonObject);

	}

	// 解析json数组的回调接口
	public interface JsonArrayCallBack {
		public void jsonArrayCallBack(JSONArray jsonArray);
	}

	// 解析json字符串的回调接口
	public interface JsonStringCallBack {
		public void jsonStringCallBack(String jsonString);
	}
	// 請求超時的回調接口
	public interface RequestTimeOutCallBack {
		public void timeOutCallBack(String timeOutString);
	}
}
ImageLoaderUtils图片加载器,为其分配内存空间:
package com.example.utils;

import android.graphics.Bitmap;
import android.support.v4.util.LruCache;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageLoader.ImageCache;

public class ImageLoaderUtils {

	private static ImageLoader imageLoader;

	public static ImageLoader getImageLoader(RequestQueue requestQueue) {	
		if (imageLoader == null) {//单例模式
			imageLoader = new ImageLoader(requestQueue, new ImageCache() {
				
				
				private LruCache cache = new LruCache(
						(int) Runtime.getRuntime().maxMemory() / 4) {//因图片很多故在此处为4,本应为8

					@Override
					protected void entryRemoved(boolean evicted, String key,
							Bitmap oldValue, Bitmap newValue) {
						super.entryRemoved(evicted, key, oldValue, newValue);
						//如果为true为存满后 挤出来的
						if (evicted) {
							oldValue.recycle();
							oldValue = null;
						}
					}

					@Override
					protected int sizeOf(String key, Bitmap value) {
						return value.getRowBytes() * value.getHeight();
						
					}

				};

				@Override
				public void putBitmap(String url, Bitmap bitmap) {
					// TODO Auto-generated method stub
					cache.put(url, bitmap);
				}

				@Override
				public Bitmap getBitmap(String url) {
					// TODO Auto-generated method stub
					return cache.get(url);
				}
			});
		}
		return imageLoader;
	}
	
	public static void LetImageLoaderToGc(){
		imageLoader=null;
	}
}

MainActivity类如下:

package com.example.android_atuoviewpager;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import com.android.volley.toolbox.NetworkImageView;
import com.example.utils.JsonUtils;
import com.example.utils.VolleyTool;
import com.example.utils.JsonUtils.JsonStringCallBack;
import com.example.utils.JsonUtils.RequestTimeOutCallBack;

import android.os.Bundle;
import android.os.Message;
import android.app.Activity;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity {

	private static final String LOG_TAG = "MainActivity";  
    public ImageHandler handler = new ImageHandler(new WeakReference(this));  
    public ViewPager viewPager; 
    private ImageAdapter imageAdapter;
    ArrayList newImageViews;
    private List imageLists;
    private NetworkImageView networkImageView;
    private ViewGroup group; // 图中小圆点Group
	private ImageView[] imageDots = null; // 小圆点数组集合
	
	// 假数据
	private String json_path = "http://open.cms.pcpop.com/Mobile/GetPop_Mobile.ashx?method=hand&Eid=8613&HandType=Index_pic#";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		  setContentView(R.layout.activity_main);  
	        //初始化iewPager的内容  
	        viewPager = (ViewPager) findViewById(R.id.main_viewpager);  
	        group = (ViewGroup) findViewById(R.id.point_group);
	        parseImageData();
	        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {  
	               
	            //配合Adapter的currentItem字段进行设置。  
	            @Override  
	            public void onPageSelected(int arg0) {  
	                handler.sendMessage(Message.obtain(handler, ImageHandler.MSG_PAGE_CHANGED, arg0, 0));  
	                int currentPosition = arg0 % newImageViews.size();
	    			for (int i = 0; i < newImageViews.size(); i++) {
	    				imageDots[currentPosition]
	    						.setBackgroundResource(R.drawable.test_greenicon);
	    				if (currentPosition != i) {
	    					imageDots[i]
	    							.setBackgroundResource(R.drawable.test_grayicon);
	    				}
	    			}
	            }  
	               
	            @Override  
	            public void onPageScrolled(int arg0, float arg1, int arg2) {  
	            }  
	               
	            //覆写该方法实现轮播效果的暂停和恢复  
	            @Override  
	            public void onPageScrollStateChanged(int arg0) {  
	                switch (arg0) {  
	                case ViewPager.SCROLL_STATE_DRAGGING:  
	                    handler.sendEmptyMessage(ImageHandler.MSG_KEEP_SILENT);  
	                    break;  
	                case ViewPager.SCROLL_STATE_IDLE:  
	                    handler.sendEmptyMessageDelayed(ImageHandler.MSG_UPDATE_IMAGE, ImageHandler.MSG_DELAY);  
	                    break;  
	                default:  
	                    break;  
	                }  
	            }  
	        });  
	        viewPager.setCurrentItem(Integer.MAX_VALUE/2);//默认在中间,使用户看不到边界  
	        //开始轮播效果  
	        handler.sendEmptyMessageDelayed(ImageHandler.MSG_BREAK_SILENT, ImageHandler.MSG_DELAY);  
	    }

	private void parseImageData() {
		JsonUtils.parseJsonString(this, json_path,
				new JsonStringCallBack() {

					@Override
					public void jsonStringCallBack(String jsonString) {
						parseJsonImage(jsonString);
						System.out.println("---->>"+imageLists.get(0).getClickUrl()+"---->>");
						imageAdapter = new ImageAdapter(newImageViews);
						viewPager.setAdapter(imageAdapter); 
						imageAdapter.notifyDataSetChanged();
					}
				}, new RequestTimeOutCallBack() {

					@Override
					public void timeOutCallBack(String timeOutString) {
						
					}
				}, VolleyTool.getInstance(this).getmRequestQueue());
	}
	/**
	 * 解析首页焦点图数据
	 * 
	 * @param jsonString
	 *            获取到的json字符串
	 * @return
	 */
	private List parseJsonImage(String jsonString) {
		imageLists = new ArrayList();
		newImageViews = new ArrayList();
		try {
			JSONObject jsonObject = new JSONObject(jsonString)
					.getJSONObject("info");
			JSONArray jsonArray = jsonObject.getJSONArray("infolist");
			for (int i = 0; i < jsonArray.length(); i++) {
				JSONObject jsonElement = jsonArray.getJSONObject(i);
				HeadImage headImage = new HeadImage();
				headImage.setIndexArtid(jsonElement.getString("IndexArtid"));
				headImage.setIndexImgurl(jsonElement.getString("IndexImgurl"));
				headImage.setClickUrl(jsonElement.getString("ClickUrl"));
				headImage.setArtType(jsonElement.getInt("ArtType"));
				imageLists.add(headImage);
			}
			for (int i = 0; i < imageLists.size(); i++) {
				networkImageView = new NetworkImageView(this);
				networkImageView.setScaleType(ScaleType.FIT_XY);
				networkImageView
						.setDefaultImageResId(R.drawable.ic_launcher);
				networkImageView.setImageUrl(
						imageLists.get(i).getIndexImgurl(), VolleyTool
								.getInstance(this).getmImageLoader());
				newImageViews.add(networkImageView);
			}
			group.removeAllViews();
			imageDots = new ImageView[imageLists.size()];
			for (int i = 0; i < imageDots.length; i++) {
				imageDots[i] = new ImageView(this);
				// 设置参数
				LayoutParams params = new LayoutParams(15, 15);
				params.gravity = Gravity.CENTER_HORIZONTAL;
				params.setMargins(6, 0, 6, 0);
				imageDots[i].setLayoutParams(params);
				imageDots[i].setPadding(20, 0, 20, 0);
				if (i == 0) {
					imageDots[i]
							.setBackgroundResource(R.drawable.test_greenicon);
				} else {
					imageDots[i]
							.setBackgroundResource(R.drawable.test_grayicon);
				}
				group.addView(imageDots[i]);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return imageLists;
	}

	public class ImageAdapter extends PagerAdapter {

		private ArrayList viewlist ;  
		   
	    public ImageAdapter(ArrayList viewlist) {  
	        this.viewlist = viewlist;  
	    }  

	    @Override  
	    public int getCount() {  
	        //设置成最大,使用户看不到边界  
	        return Integer.MAX_VALUE;  
	    }  

	    @Override  
	    public boolean isViewFromObject(View arg0, Object arg1) {  
	        return arg0==arg1;  
	    }  
	     @Override    
	     public void destroyItem(ViewGroup container, int position,    
	             Object object) {    
	         //Warning:不要在这里调用removeView  
	     }    
	     @Override    
	     public Object instantiateItem(ViewGroup container, int position) {  
	         //对ViewPager页号求模取出View列表中要显示的项  
	         position %= viewlist.size();  
	         if (position<0){  
	             position = viewlist.size()+position;  
	         }  
	         ImageView view = viewlist.get(position);  
	         //如果View已经在之前添加到了一个父组件,则必须先remove,否则会抛出IllegalStateException。  
	         ViewParent vp =view.getParent();  
	         if (vp!=null){  
	             ViewGroup parent = (ViewGroup)vp;  
	             parent.removeView(view);  
	         }  
	         container.addView(view);    
	         //add listeners here if necessary  
	         return view;    
	     } 
	}
}

源码下载地址:

http://download.csdn.net/detail/shr957250701/8168307




你可能感兴趣的:(Android)