***需要下载Volley.jar包***
MainActivity
package com.example.administrator.tt; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; import android.view.LayoutInflater; import android.widget.LinearLayout; import com.example.administrator.tt.view.Advertisements; import com.example.administrator.tt.volley.RequestManager; public class MainActivity extends Activity { private LinearLayout llAdvertiseBoard; private LayoutInflater inflater; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); RequestManager.init(this); inflater = LayoutInflater.from(this); initViews(); } private void initViews() { llAdvertiseBoard = (LinearLayout) this.findViewById(R.id.llAdvertiseBoard); JSONArray advertiseArray = new JSONArray(); try { JSONObject head_img0 = new JSONObject(); head_img0.put("head_img","http://pic.nipic.com/2008-08-12/200881211331729_2.jpg"); JSONObject head_img1 = new JSONObject(); head_img1.put("head_img","http://pic1.ooopic.com/uploadfilepic/sheji/2010-01-12/OOOPIC_1982zpwang407_20100112ae3851a13c83b1c4.jpg"); JSONObject head_img2 = new JSONObject(); head_img2.put("head_img","http://pic1.ooopic.com/uploadfilepic/sheji/2009-09-12/OOOPIC_wenneng837_200909122b2c8368339dd52a.jpg"); JSONObject head_img3 = new JSONObject(); head_img3.put("head_img","http://pic.nipic.com/2008-08-12/200881211331729_2.jpg"); advertiseArray.put(head_img0); advertiseArray.put(head_img1); advertiseArray.put(head_img2); advertiseArray.put(head_img3); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } llAdvertiseBoard.addView(new Advertisements(this, true, inflater, 3000).initView(advertiseArray)); } }
AdvertisementAdapter
package com.example.administrator.tt.adapter; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.json.JSONArray; import android.content.Context; import android.content.Intent; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.Toast; import com.example.administrator.tt.R; import com.example.administrator.tt.utils.ImageLoaderUtil; /** * 广告轮播adapter *@author dong *@data 2015年3月8日下午3:46:35 *@contance dong854163@163.com */ public class AdvertisementAdapter extends PagerAdapter { private Context context; private List<View> views; JSONArray advertiseArray; public AdvertisementAdapter() { super(); // TODO Auto-generated constructor stub } public AdvertisementAdapter(Context context, List<View> views, JSONArray advertiseArray) { this.context = context; this.views = views; this.advertiseArray = advertiseArray; } @Override public int getCount() { // TODO Auto-generated method stub return views.size(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return (arg0 == arg1); } @Override public void destroyItem(View container, int position, Object object) { ((ViewPager) container).removeView(views.get(position)); } @Override public Object instantiateItem(View container, int position) { ((ViewPager) container).addView(views.get(position), 0); final int POSITION = position; View view = views.get(position); try { String head_img = advertiseArray.optJSONObject(position).optString("head_img"); ImageView ivAdvertise = (ImageView) view.findViewById(R.id.ivAdvertise); ImageLoaderUtil.getImage(context, ivAdvertise, head_img, R.drawable.ic_launcher, R.drawable.ic_launcher, 0, 0); ivAdvertise.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast.makeText(context, "第"+POSITION+"个广告图片被点击", Toast.LENGTH_LONG).show(); } }); } catch (Exception e) { e.printStackTrace(); } return view; } }ImageLoaderUtil
package com.example.administrator.tt.utils; import java.lang.reflect.Field; import android.content.Context; import android.util.DisplayMetrics; import android.util.Log; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.ImageLoader.ImageListener; import com.example.administrator.tt.volley.RequestManager; /** *@author dong *@date 2015年3月8日下午2:16:53 volley框架获取图片 */ public class ImageLoaderUtil { public static void getImage(Context context , ImageView v , String iamgeUrl , int defaultImageResId, int errorImageResId){ getImage(context, v, iamgeUrl, defaultImageResId, errorImageResId, 0, 0); } public static void getImage(Context context , ImageView v , String iamgeUrl , int defaultImageResId, int errorImageResId,int maxWidth,int maxHeight){ try { /*volley*/ ImageLoader imageLoader = RequestManager.getImageLoader(); ImageListener listener = ImageLoader.getImageListener(v, defaultImageResId, errorImageResId); ImageSize imageSize = getImageViewWidth(v); if(maxWidth != 0 && maxHeight != 0){ imageSize.width = maxWidth; imageSize.height = maxHeight; } Log.d("imageSize", "width>>"+imageSize.width+"height>>"+imageSize.height); imageLoader.get(iamgeUrl, listener,imageSize.width,imageSize.height); } catch (Exception e) { // TODO: handle exception } } /** * 根据ImageView获得适当的压缩的宽和高 * * @param imageView * @return */ private static ImageSize getImageViewWidth(ImageView imageView) { ImageSize imageSize = new ImageSize(); final DisplayMetrics displayMetrics = imageView.getContext().getResources().getDisplayMetrics(); final LayoutParams params = imageView.getLayoutParams(); int width = params.width == LayoutParams.WRAP_CONTENT ? 0 : imageView .getWidth(); // Get actual image width if (width <= 0) width = params.width; // Get layout width parameter if (width <= 0) width = getImageViewFieldValue(imageView, "mMaxWidth"); // Check // maxWidth // parameter if (width <= 0) // width = displayMetrics.widthPixels; width = 350; int height = params.height == LayoutParams.WRAP_CONTENT ? 0 : imageView .getHeight(); // Get actual image height if (height <= 0) height = params.height; // Get layout height parameter if (height <= 0) height = getImageViewFieldValue(imageView, "mMaxHeight"); // Check // maxHeight // parameter if (height <= 0) // height = displayMetrics.heightPixels; height = 350; imageSize.width = width; imageSize.height = height; return imageSize; } private static class ImageSize { int width; int height; } /** * 反射获得ImageView设置的最大宽度和高度 * * @param object * @param fieldName * @return */ private static int getImageViewFieldValue(Object object, String fieldName) { int value = 0; try { Field field = ImageView.class.getDeclaredField(fieldName); field.setAccessible(true); int fieldValue = (Integer) field.get(object); if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE) { value = fieldValue; } } catch (Exception e) { } return value; } }
Advertisements
package com.example.administrator.tt.view; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.json.JSONArray; import android.content.Context; import android.os.Handler; import android.os.Message; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.LinearLayout; import com.example.administrator.tt.R; import com.example.administrator.tt.adapter.AdvertisementAdapter; /** *@author dong *@version 2015-3-8下午4:33:39 */ public class Advertisements implements OnPageChangeListener { private ViewPager vpAdvertise; private Context context; private LayoutInflater inflater; private boolean fitXY; private int timeDratioin;//多长时间切换一次pager List<View> views; // 底部小点图片 private ImageView[] dots; // 记录当前选中位置 private int currentIndex; Timer timer; TimerTask task; int count = 0; private Handler runHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case 0x01: int currentPage = (Integer) msg.obj; setCurrentDot(currentPage); vpAdvertise.setCurrentItem(currentPage); break; } }; }; public Advertisements(Context context, boolean fitXY, LayoutInflater inflater , int timeDratioin) { this.context = context; this.fitXY = fitXY; this.inflater = inflater; this.timeDratioin = timeDratioin; } public View initView(final JSONArray advertiseArray){ View view = inflater.inflate(R.layout.advertisement_board, null); vpAdvertise = (ViewPager) view.findViewById(R.id.vpAdvertise); vpAdvertise.setOnPageChangeListener(this); views = new ArrayList<View>(); LinearLayout ll = (LinearLayout) view.findViewById(R.id.ll);//获取轮播图片的点的parent,用于动态添加要显示的点 for(int i = 0 ; i < advertiseArray.length() ; i ++){ if(fitXY){ views.add(inflater.inflate(R.layout.advertisement_item_fitxy, null)); }else { views.add(inflater.inflate(R.layout.advertisement_item_fitcenter, null)); } ll.addView(inflater.inflate(R.layout.advertisement_board_dot, null)); } initDots(view , ll); AdvertisementAdapter adapter = new AdvertisementAdapter(context , views , advertiseArray); vpAdvertise.setOffscreenPageLimit(3); vpAdvertise.setAdapter(adapter); timer = new Timer(); task = new TimerTask() { @Override public void run() { int currentPage = count%advertiseArray.length(); count++; Message msg = Message.obtain(); msg.what = 0x01; msg.obj = currentPage; runHandler.sendMessage(msg); } }; timer.schedule(task, 0, timeDratioin); return view; } private void initDots(View view, LinearLayout ll) { dots = new ImageView[views.size()]; // 循环取得小点图片 for (int i = 0; i < views.size(); i++) { dots[i] = (ImageView) ll.getChildAt(i); dots[i].setEnabled(true);// 都设为灰色 } currentIndex = 0; dots[currentIndex].setEnabled(false);// 设置为黄色,即选中状态 } private void setCurrentDot(int position) { if (position < 0 || position > views.size() - 1 || currentIndex == position) { return; } dots[position].setEnabled(false); dots[currentIndex].setEnabled(true); currentIndex = position; } @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageSelected(int position) { // TODO Auto-generated method stub count = position; setCurrentDot(position); } }BitmapLruCache
package com.example.administrator.tt.volley; import android.graphics.Bitmap; import android.util.Log; import android.util.LruCache; import com.android.volley.toolbox.ImageLoader; public class BitmapLruCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache { public BitmapLruCache(int maxSize) { super(maxSize); } @Override protected int sizeOf(String key, Bitmap bitmap) { return bitmap.getRowBytes() * bitmap.getHeight(); } @Override public Bitmap getBitmap(String url) { return get(url); } // @Override // protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, // Bitmap newValue) { // Logger.d("BitmapLruCache","bitmap recycle"); // if(evicted) // oldValue.recycle(); // super.entryRemoved(evicted, key, oldValue, newValue); // } @Override public void putBitmap(String url, Bitmap bitmap) { put(url, bitmap); Log.d("BitmapLruCache", "bitmap size1>>"+bitmap.getRowBytes() * bitmap.getHeight()+"size2>>"+bitmap.getByteCount()); } }
RequestManager
package com.example.administrator.tt.volley; import android.app.ActivityManager; import android.content.Context; import com.android.volley.DefaultRetryPolicy; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.Volley; public class RequestManager { private static RequestQueue mRequestQueue; private static ImageLoader mImageLoader; private RequestManager() { // no instances } public static void init(Context context) { if(mRequestQueue == null){ mRequestQueue = getRequestQueue(context); } if(mImageLoader == null){ int memClass = ((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass(); // Use 1/8th of the available memory for this memory cache. int cacheSize = 1024 * 1024 * memClass / 8; mImageLoader = new ImageLoader(mRequestQueue,new BitmapLruCache(cacheSize)); } } public static RequestQueue getRequestQueue(Context context) { if (mRequestQueue == null) mRequestQueue = Volley.newRequestQueue(context); return mRequestQueue; } public static void addRequest(Request<?> request, Object tag) { if (tag != null) { request.setTag(tag); } request.setRetryPolicy(new DefaultRetryPolicy(8000, 0, 1f)); mRequestQueue.add(request); } public static void cancelAll(Object tag) { mRequestQueue.cancelAll(tag); } /** * Returns instance of ImageLoader initialized with {@see FakeImageCache} * which effectively means that no memory caching is used. This is useful * for images that you know that will be show only once. * * @return */ public static ImageLoader getImageLoader() { if (mImageLoader != null) { return mImageLoader; } else { throw new IllegalStateException("ImageLoader not initialized"); } } }//===============================================================
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF" android:orientation="vertical" > <LinearLayout android:id="@+id/llAdvertiseBoard" android:layout_width="match_parent" android:layout_height="160dip" android:orientation="vertical"/> </LinearLayout>advertisement_board.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/base_bg_color" android:gravity="center_horizontal" android:orientation="vertical" > <android.support.v4.view.ViewPager android:id="@+id/vpAdvertise" android:layout_width="match_parent" android:layout_height="150dip" /> <LinearLayout android:id="@+id/ll" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:orientation="horizontal" android:layout_marginBottom="@dimen/margin_Size10"> </LinearLayout> </RelativeLayout>advertisement_board_dot.xml
<?xml version="1.0" encoding="utf-8"?> <ImageView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:clickable="true" android:padding="10dip" android:src="@drawable/point_yellow" > </ImageView>advertisement_item_fitcenter.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="150dip" android:background="@color/base_bg_color" android:orientation="vertical" > <ImageView android:id="@+id/ivAdvertise" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:scaleType="fitCenter" android:src="@drawable/ic_launcher"/> </RelativeLayout>advertisement_item_fitxy.xml
<****清单配置文件******<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="150dip" android:background="@color/base_bg_color" android:orientation="vertical" > <ImageView android:id="@+id/ivAdvertise" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" android:scaleType="fitXY" android:src="@drawable/ic_launcher"/> </RelativeLayout><uses-permission android:name="android.permission.INTERNET"/>>