广告条效果实现----ViewPager加载大图片(LruCache)以及定时刷新

先来看看效果:

 

1、广告条效果应该是使用的比较广泛的一个效果了,使用的基本构架就是一个ViewPager组件,在低版本的Android中,我们需要手动导入v4 jar包才可以使用。

 

2、ViewPager的加载方式与listview的加载方式不太一样,对于listview,其中总是会使用到子view的复用,但是对于viewpager,动态滑动的时候,它只保持三个页面在内存中,也就是:当前显示页面,前一个页面和后一个页面;其他页面都被销毁释放掉。

 

3、对于大图片的加载,如果不做处理,可能一两张图片就会导致OOM,应用挂掉;在早期版本中,2.3以前,经常的做法是使用软引用和弱引用集合来处理在内存中加载图片,但是对于Android3.0的版本,Android系统偏向于直接回收掉软引用的对象而不是软引用的成员,这就导致了本做法不再适用。但是好在Android系统同时给出了一个比较好的工具让我们来处理图片的加载:LruCache。这个类非常适合用来缓存图片,它的主要算法原理是把最近使用的对象用强引用存储在 LinkedHashMap 中,并且把最近最少使用的对象在缓存值达到预设定值之前从内存中移除。

 

4、大图片加载的老生长提的问题就是在加载之前先使用bitmapfactory来调整图片的大小,这里涉及到BitmapFactory.Options.inJustDecodeBounds = true;通过options.outHeight;和options.outWidth;拿到图片的宽高,然后再根据屏幕的宽高来缩放图片,达到压缩的效果。

 

5、另外一个关于ViewPager的小问题就是在于直接调用adapter.notifydatasetchanged()方法,无法刷新viewpager的数据;这里解决的版本有两个:

a.   重写pageadapter的getItemPosition方法,让其直接返回POSITION_NONE,这时候再调用notifydatasetchanged则可以起作用

b.   在更新完数据之后,调用一个handler发送对应的message,来手动刷新局部数据,这种方式比较推荐,实际上也可以用于listview的局部刷新,比较通用。

 

6、这里还实现了一个两边无线循环滑动的效果,实际上的图片只有六张,但是我们可以无线往两边滑动,实际上两边的数量是integer.max_value/2,

核心思想在于getCount方法返回一个integer.max)value,然后对于postion的处理都使用position%6,这样来实现,具体细节可以参看代码

 

好,废话说完,上代码:

MainActivity:

 

[java]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. package com.example.advertisebardemo;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.concurrent.Executors;  
  6. import java.util.concurrent.ScheduledExecutorService;  
  7.   
  8. import android.app.Activity;  
  9. import android.content.res.Resources;  
  10. import android.graphics.Bitmap;  
  11. import android.graphics.Bitmap.Config;  
  12. import android.graphics.BitmapFactory;  
  13. import android.graphics.BitmapFactory.Options;  
  14. import android.os.AsyncTask;  
  15. import android.os.Build;  
  16. import android.os.Bundle;  
  17. import android.os.Handler;  
  18. import android.os.Message;  
  19. import android.support.v4.util.LruCache;  
  20. import android.support.v4.view.PagerAdapter;  
  21. import android.support.v4.view.ViewPager;  
  22. import android.support.v4.view.ViewPager.OnPageChangeListener;  
  23. import android.text.format.Formatter;  
  24. import android.view.MotionEvent;  
  25. import android.view.View;  
  26. import android.view.View.OnTouchListener;  
  27. import android.view.ViewGroup;  
  28. import android.view.WindowManager;  
  29. import android.widget.ImageView;  
  30. import android.widget.LinearLayout;  
  31. import android.widget.TextView;  
  32.   
  33. public class MainActivity extends Activity {  
  34.   
  35.     private ViewPager viewPager;  
  36.     private int[] ids = { R.drawable.a, R.drawable.b, R.drawable.c,  
  37.             R.drawable.d, R.drawable.e, R.drawable.f };  
  38.     private List<ImageView> imageViews = new ArrayList<ImageView>();  
  39.     private MyAdapter adapter;  
  40.     private Options options;  
  41.     private int screenWidth;  
  42.     private int screenHeight;  
  43.     private LruCache<String, Bitmap> mMemoryCache;  
  44.     private WindowManager wm;  
  45.     private int wWidth;  
  46.     private int wHeight;  
  47.     /** 
  48.      * 设置一个标志位来判断是否继续自动滑动 
  49.      */  
  50.     private boolean isRunning = false;  
  51.   
  52.     private int lastPointPosition;  
  53.     private boolean operationFlag;  
  54.     /** 
  55.      * 线程池对象 
  56.      */  
  57.     private ScheduledExecutorService pool;  
  58.     private Object[] objs;  
  59.     private String[] descriptions = { "图片描述一""图片描述二""图片描述三""图片描述四",  
  60.             "图片描述五""图片描述六" };  
  61.   
  62.     private LinearLayout ll_points;  
  63.     private TextView tv_des;  
  64.   
  65.     private Handler handler = new Handler() {  
  66.   
  67.         @Override  
  68.         public void handleMessage(Message msg) {  
  69.             super.handleMessage(msg);  
  70.             switch (msg.what) {  
  71.             case 0:  
  72.                 // adapter.notifyDataSetChanged();  
  73.                 // 不用adapter.notifyDataSetChanged(),而使用局部刷新的方法  
  74.                 int tag = Integer.parseInt(String  
  75.                         .valueOf(((Object[]) msg.obj)[0]));  
  76.                 ImageView iv = (ImageView) viewPager.findViewWithTag(tag);  
  77.                 iv.setImageBitmap((Bitmap) ((Object[]) msg.obj)[1]);  
  78.                 break;  
  79.   
  80.             case 1:  
  81.                 viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);// 往后移动一页  
  82.                 if (isRunning) {  
  83.                     handler.sendEmptyMessageDelayed(12000);  
  84.                 }  
  85.                 break;  
  86.             case 2:  
  87.   
  88.                 break;  
  89.             default:  
  90.                 break;  
  91.             }  
  92.   
  93.         }  
  94.   
  95.     };  
  96.   
  97.     @Override  
  98.     protected void onCreate(Bundle savedInstanceState) {  
  99.         super.onCreate(savedInstanceState);  
  100.         setContentView(R.layout.activity_main);  
  101.   
  102.         // 初始化imageviews集合  
  103.         initImageViews();  
  104.   
  105.         // 初始化布局文件中的view  
  106.         initViews();  
  107.   
  108.         // 初始化窗口参数  
  109.         initWindowParams();  
  110.   
  111.         // 初始化lrucache  
  112.         initLruCache();  
  113.   
  114.         // 三个线程的线程池  
  115.         pool = Executors.newScheduledThreadPool(3);  
  116.   
  117.         // 初始化一个bitmapfactory选项对象  
  118.         options = new Options();  
  119.   
  120.         // 初始化小点  
  121.         initPointGroup();  
  122.   
  123.         notifyAdapter();  
  124.   
  125.         // 设置初始的时候在Integer一半附近的第一张图的位置上  
  126.         viewPager.setCurrentItem(Integer.MAX_VALUE / 2  
  127.                 + (Integer.MAX_VALUE / 2) % ids.length);  
  128.   
  129.         // 自动滑动标志位置为true  
  130.         isRunning = true;  
  131.   
  132.         // 给viewpager添加滑动监听器  
  133.         setViewPagerOnageChangeListener();  
  134.   
  135.         // msg.what=1,延迟2秒  
  136.         handler.sendEmptyMessageDelayed(12000);  
  137.     }  
  138.   
  139.     private void setViewPagerOnageChangeListener() {  
  140.         viewPager.setOnPageChangeListener(new OnPageChangeListener() {  
  141.   
  142.             /** 
  143.              * 当页面被选中的时候回调的方法 
  144.              */  
  145.             @Override  
  146.             public void onPageSelected(int position) {  
  147.                 ll_points.getChildAt(lastPointPosition % 6).setEnabled(false);  
  148.                 ll_points.getChildAt(position % 6).setEnabled(true);  
  149.                 lastPointPosition = position;  
  150.                 // 设置对应的描述文字  
  151.                 tv_des.setText(descriptions[position % 6]);  
  152.             }  
  153.   
  154.             @Override  
  155.             public void onPageScrolled(int position, float positionOffset,  
  156.                     int positionOffsetPixels) {  
  157.                 // TODO Auto-generated method stub  
  158.   
  159.             }  
  160.   
  161.             @Override  
  162.             public void onPageScrollStateChanged(int state) {  
  163.                 // TODO Auto-generated method stub  
  164.   
  165.             }  
  166.         });  
  167.   
  168.     }  
  169.   
  170.     private void initPointGroup() {  
  171.         LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(  
  172.                 1515);  
  173.         layoutParams.setMargins(152155);  
  174.         for (int i = 0; i < ids.length; i++) {  
  175.             ImageView point = new ImageView(this);  
  176.             point.setBackgroundResource(R.drawable.point_bg);  
  177.             // 设置位置参数  
  178.             point.setLayoutParams(layoutParams);  
  179.             if (i == 0) {  
  180.                 point.setEnabled(true);  
  181.             } else {  
  182.                 point.setEnabled(false);  
  183.             }  
  184.             ll_points.addView(point);  
  185.         }  
  186.     }  
  187.   
  188.     private void initLruCache() {  
  189.         // lrucache通过构造函数传入缓存值,以kb为单位,因为这里除以了1204  
  190.         int maxMem = (int) (Runtime.getRuntime().maxMemory() / 1024);// 本来是1024,这里除以1024应该是为了防止int类型溢出  
  191.         int totalMemory = (int) (Runtime.getRuntime().totalMemory());  
  192.         int freeMemory = (int) (Runtime.getRuntime().freeMemory());  
  193.   
  194.         System.out.println("totalMemory="  
  195.                 + Formatter.formatFileSize(this, totalMemory));  
  196.         System.out.println("freeMemory="  
  197.                 + Formatter.formatFileSize(this, freeMemory));  
  198.   
  199.         int cacheSize = maxMem / 2;  
  200.         System.out.println("分配给LruCache的内存大小:"  
  201.                 + Formatter.formatFileSize(this, cacheSize * 1024));  
  202.         mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {  
  203.   
  204.             @Override  
  205.             protected int sizeOf(String key, Bitmap bitmap) {  
  206.                 // return super.sizeOf(key, value);  
  207.                 // 重写此方法来衡量每张图片的大小,默认返回图片数量。  
  208.   
  209.                 // 总像素数乘以每个像素占的字节数,除以1024  
  210.                 return bitmap.getWidth() * bitmap.getHeight()  
  211.                         * getBytesPerPixel(bitmap.getConfig()) / 1024;  
  212.                 // 下面这一句要求API 12  
  213.                 // return bitmap.getByteCount() / 1024;// 这里和上面都除以1024,达到一致即可  
  214.             }  
  215.   
  216.             @Override  
  217.             protected void entryRemoved(boolean evicted, String key,  
  218.                     Bitmap oldValue, Bitmap newValue) {  
  219.                 super.entryRemoved(evicted, key, oldValue, newValue);  
  220.   
  221.             }  
  222.   
  223.         };  
  224.     }  
  225.   
  226.     /** 
  227.      * 获取每个像素所占用的Byte数 
  228.      *  
  229.      * @param config 
  230.      * @return 
  231.      */  
  232.     public static int getBytesPerPixel(Config config) {  
  233.         if (config == Config.ARGB_8888) {  
  234.             return 4;  
  235.         } else if (config == Config.RGB_565) {  
  236.             return 2;  
  237.         } else if (config == Config.ARGB_4444) {  
  238.             return 2;  
  239.         } else if (config == Config.ALPHA_8) {  
  240.             return 1;  
  241.         }  
  242.         return 1;  
  243.     }  
  244.   
  245.     private void initWindowParams() {  
  246.         wm = (WindowManager) getSystemService(WINDOW_SERVICE);  
  247.         wWidth = wm.getDefaultDisplay().getWidth();  
  248.         wHeight = wm.getDefaultDisplay().getHeight();  
  249.     }  
  250.   
  251.     private void initViews() {  
  252.         ll_points = (LinearLayout) findViewById(R.id.ll_points);  
  253.         tv_des = (TextView) findViewById(R.id.tv_des);  
  254.         tv_des.setText(descriptions[0]);  
  255.         viewPager = (ViewPager) findViewById(R.id.viewPager);  
  256.         // TODO 自适应屏幕的viewpager大小的参数  
  257.     }  
  258.   
  259.     private void initImageViews() {  
  260.         for (int i = 0; i < ids.length; i++) {  
  261.             imageViews.add(new ImageView(this));  
  262.         }  
  263.     }  
  264.   
  265.     @Override  
  266.     protected void onDestroy() {  
  267.         // TODO Auto-generated method stub  
  268.         super.onDestroy();  
  269.         isRunning = false;  
  270.         // android.os.Debug.stopMethodTracing();  
  271.     }  
  272.   
  273.     /** 
  274.      * 将对应key的bitmap加入到cache中 
  275.      *  
  276.      * @param key 
  277.      * @param bitmap 
  278.      */  
  279.     public void addBitmapToMemoryCache(String key, Bitmap bitmap) {  
  280.         if (getBitmapFromMemCache(key) == null) {  
  281.             mMemoryCache.put(key, bitmap);  
  282.         }  
  283.     }  
  284.   
  285.     /** 
  286.      * 从cache中取出对应key的bitmap对象 
  287.      *  
  288.      * @param key 
  289.      * @return 
  290.      */  
  291.     public Bitmap getBitmapFromMemCache(String key) {  
  292.         return mMemoryCache.get(key);  
  293.     }  
  294.   
  295.     /** 
  296.      * 设置apdater的方法 
  297.      */  
  298.     private void notifyAdapter() {  
  299.         if (adapter == null) {  
  300.             adapter = new MyAdapter();  
  301.             viewPager.setAdapter(adapter);  
  302.         } else {  
  303.             /* 
  304.              * 发现下面这一句并不能起到刷新数据的作用, 除非将 getItemPosition方法的返回值设为POSITION_NONE 
  305.              */  
  306.             // adapter.notifyDataSetChanged();  
  307.         }  
  308.     }  
  309.   
  310.     public void loadBitmap(int resId, ImageView imageView) {  
  311.         final String imageKey = String.valueOf(resId);  
  312.         final Bitmap bitmap = getBitmapFromMemCache(imageKey);  
  313.         if (bitmap != null) {  
  314.             imageView.setImageBitmap(bitmap);  
  315.         } else {  
  316.             // imageView.setImageResource(R.drawable.ic_launcher);// 默认  
  317.   
  318.             // 这里是使用AsyncTask的方法  
  319.             BitmapWorkerTask task = new BitmapWorkerTask();  
  320.             task.execute(resId);  
  321.   
  322.             // 下面是使用线程池的方式,两种方式都可用,线程池可能对于网络加载会好一点  
  323.             // pool.submit(new MyRunnable(resId));  
  324.   
  325.         }  
  326.     }  
  327.   
  328.     class MyRunnable implements Runnable {  
  329.         private int id;  
  330.   
  331.         public MyRunnable() {  
  332.             super();  
  333.         }  
  334.   
  335.         public MyRunnable(int id) {  
  336.             super();  
  337.             this.id = id;  
  338.         }  
  339.   
  340.         @Override  
  341.         public void run() {  
  342.             final Bitmap bitmap = decodeSampledBitmapFromResource(  
  343.                     getResources(), id, wWidth, wHeight);  
  344.             // System.out.println("wWidth=" + wWidth);  
  345.             // System.out.println("wHeight=" + wHeight);  
  346.             addBitmapToMemoryCache(String.valueOf(id), bitmap);  
  347.             Message msg = Message.obtain();  
  348.             msg.what = 0;  
  349.             objs = new Object[] { id, bitmap };  
  350.             msg.obj = objs;  
  351.             handler.sendMessage(msg);  
  352.         }  
  353.   
  354.     }  
  355.   
  356.     class BitmapWorkerTask extends AsyncTask<Integer, Void, Bitmap> {  
  357.         // 在后台加载图片。  
  358.   
  359.         @Override  
  360.         protected Bitmap doInBackground(Integer... params) {  
  361.             final Bitmap bitmap = decodeSampledBitmapFromResource(  
  362.                     getResources(), params[0], wWidth, wHeight);  
  363.             // System.out.println("wWidth=" + wWidth);  
  364.             // System.out.println("wHeight=" + wHeight);  
  365.             addBitmapToMemoryCache(String.valueOf(params[0]), bitmap);  
  366.             Message msg = Message.obtain();  
  367.             msg.what = 0;  
  368.             objs = new Object[] { params[0], bitmap };  
  369.             msg.obj = objs;  
  370.             handler.sendMessage(msg);  
  371.             return bitmap;  
  372.         }  
  373.     }  
  374.   
  375.     public static Bitmap decodeSampledBitmapFromResource(Resources res,  
  376.             int resId, int reqWidth, int reqHeight) {  
  377.         // 第一次解析将inJustDecodeBounds设置为true,来获取图片大小  
  378.         final BitmapFactory.Options options = new BitmapFactory.Options();  
  379.         options.inJustDecodeBounds = true;  
  380.         BitmapFactory.decodeResource(res, resId, options);  
  381.         // 调用上面定义的方法计算inSampleSize值  
  382.         options.inSampleSize = calculateInSampleSize(options, reqWidth,  
  383.                 reqHeight);  
  384.   
  385.         System.out.println("inSampleSize=" + options.inSampleSize);  
  386.   
  387.         // 使用获取到的inSampleSize值再次解析图片  
  388.         options.inJustDecodeBounds = false;  
  389.         return BitmapFactory.decodeResource(res, resId, options);  
  390.     }  
  391.   
  392.     public static int calculateInSampleSize(BitmapFactory.Options options,  
  393.             int reqWidth, int reqHeight) {  
  394.         // 源图片的高度和宽度  
  395.         final int height = options.outHeight;  
  396.         final int width = options.outWidth;  
  397.   
  398.         // System.out.println("height=" + height);  
  399.         // System.out.println("width=" + width);  
  400.   
  401.         int inSampleSize = 1;  
  402.         if (height > reqHeight || width > reqWidth) {  
  403.             // 计算出实际宽高和目标宽高的比率  
  404.             final int heightRatio = Math.round((float) height  
  405.                     / (float) reqHeight);  
  406.             final int widthRatio = Math.round((float) width / (float) reqWidth);  
  407.             // 选择宽和高中最小的比率作为inSampleSize的值,这样可以保证最终图片的宽和高  
  408.             // 一定都会大于等于目标的宽和高。  
  409.             // inSampleSize = heightRatio < widthRatio ? heightRatio :  
  410.             // widthRatio;  
  411.   
  412.             // 这里我们选择宽度对其的方式,所以缩放比选则宽度的比值  
  413.             inSampleSize = widthRatio;  
  414.         }  
  415.         return inSampleSize;  
  416.     }  
  417.   
  418.     private class MyAdapter extends PagerAdapter {  
  419.   
  420.         @Override  
  421.         public int getCount() {  
  422.             // return ids.length;  
  423.             return Integer.MAX_VALUE;  
  424.         }  
  425.   
  426.         @Override  
  427.         public boolean isViewFromObject(View view, Object object) {  
  428.             // TODO Auto-generated method stub  
  429.             return view == object;  
  430.         }  
  431.   
  432.         @Override  
  433.         public Object instantiateItem(ViewGroup container, int position) {  
  434.             ImageView imageView = imageViews.get(position % 6);  
  435.             container.addView(imageView);  
  436.             loadBitmap(ids[position % 6], imageView);  
  437.             // 把id与imageview通过setTag方法挂钩起来  
  438.             imageView.setTag(ids[position % 6]);  
  439.   
  440.             int totalMemory = (int) (Runtime.getRuntime().totalMemory());// 本来是1024,这里除以1024应该是为了防止int类型溢出  
  441.             int freeMemory = (int) (Runtime.getRuntime().freeMemory());// 本来是1024,这里除以1024应该是为了防止int类型溢出  
  442.   
  443.             System.out.println("totalMemory="  
  444.                     + Formatter.formatFileSize(MainActivity.this, totalMemory));  
  445.             System.out.println("freeMemory="  
  446.                     + Formatter.formatFileSize(MainActivity.this, freeMemory));  
  447.   
  448.             return imageView;  
  449.         }  
  450.   
  451.         @Override  
  452.         public void destroyItem(ViewGroup container, int position, Object object) {  
  453.             container.removeView((View) object);  
  454.             object = null;  
  455.         }  
  456.   
  457.         // /**  
  458.         // * 这样返回一个position_none之后,实现了viewpager的动态刷新,但是也带来了一些问题  
  459.         // */  
  460.         // @Override  
  461.         // public int getItemPosition(Object object) {  
  462.         // // TODO Auto-generated method stub  
  463.         // // return super.getItemPosition(object);  
  464.         // return POSITION_NONE;  
  465.         // }  
  466.   
  467.     }  
  468.   
  469. }  



 

 

 

布局文件:

 

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context="${relativePackage}.${activityClass}" >  
  6.   
  7.   
  8.     <android.support.v4.view.ViewPager  
  9.         android:id="@+id/viewPager"  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="202.5dp"  
  12.         android:layout_gravity="top" />  
  13.   
  14.   
  15.     <LinearLayout  
  16.         android:layout_width="fill_parent"  
  17.         android:layout_height="wrap_content"  
  18.         android:layout_alignBottom="@id/viewPager"  
  19.         android:background="#66ffffff"  
  20.         android:gravity="bottom"  
  21.         android:orientation="vertical" >  
  22.   
  23.   
  24.         <TextView  
  25.             android:id="@+id/tv_des"  
  26.             android:layout_width="fill_parent"  
  27.             android:layout_height="wrap_content"  
  28.             android:gravity="center_horizontal"  
  29.             android:textSize="15sp" />  
  30.   
  31.   
  32.         <LinearLayout  
  33.             android:id="@+id/ll_points"  
  34.             android:layout_width="fill_parent"  
  35.             android:layout_height="wrap_content"  
  36.             android:gravity="center_horizontal"  
  37.             android:orientation="horizontal" >  
  38.         </LinearLayout>  
  39.     </LinearLayout>  
  40.   
  41. </RelativeLayout>  



 

 

point_bg.xml:

 

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3.   
  4.     <item android:drawable="@drawable/point_normal" android:state_enabled="false"></item>  
  5.     <item android:drawable="@drawable/point_focused" android:state_enabled="true"></item>  
  6.   
  7. </selector>  



 

 

point_normal.xml:

 

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:shape="oval" >  
  4.   
  5.   
  6.     <size  
  7.         android:height="5dp"  
  8.         android:width="5dp" />  
  9.   
  10.   
  11.     <solid android:color="#55eeeeee" />  
  12.   
  13.   
  14. </shape>  



 

 

point_focused.xml:

 

[html]  view plain  copy
 
  在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:shape="oval" >  
  4.   
  5.   
  6.     <size  
  7.         android:height="5dp"  
  8.         android:width="5dp" />  
  9.   
  10.   
  11.     <solid android:color="#ffffffff" />  
  12.   
  13.   
  14. </shape>  

猜你喜欢

转载自lishuaishuai.iteye.com/blog/2290870
今日推荐