当前位置: 移动技术网 > IT编程>移动开发>Android > Android App中实现相册瀑布流展示的实例分享

Android App中实现相册瀑布流展示的实例分享

2019年07月24日  | 移动技术网IT编程  | 我要评论

魔岩三杰现状,艾邦客,台风狮子山

传统界面的布局方式总是行列分明、坐落有序的,这种布局已是司空见惯,在不知不觉中大家都已经对它产生了审美疲劳。这个时候瀑布流布局的出现,就给人带来了耳目一新的感觉,这种布局虽然看上去貌似毫无规律,但是却有一种说不上来的美感,以至于涌现出了大批的网站和应用纷纷使用这种新颖的布局来设计界面。
记得我在之前已经写过一篇关于如何在android上实现照片墙功能的文章了,但那个时候是使用的gridview来进行布局的,这种布局方式只适用于“墙”上的每张图片大小都相同的情况,如果图片的大小参差不齐,在gridview中显示就会非常的难看。而使用瀑布流的布局方式就可以很好地解决这个问题,因此今天我们也来赶一下潮流,看看如何在android上实现瀑布流照片墙的功能。
首先还是讲一下实现原理,瀑布流的布局方式虽然看起来好像排列的很随意,其实它是有很科学的排列规则的。整个界面会根据屏幕的宽度划分成等宽的若干列,由于手机的屏幕不是很大,这里我们就分成三列。每当需要添加一张图片时,会将这张图片的宽度压缩成和列一样宽,再按照同样的压缩比例对图片的高度进行压缩,然后在这三列中找出当前高度最小的一列,将图片添加到这一列中。之后每当需要添加一张新图片时,都去重复上面的操作,就会形成瀑布流格局的照片墙,示意图如下所示。

201648235457901.png (347×459)

听我这么说完后,你可能会觉得瀑布流的布局非常简单嘛,只需要使用三个linearlayout平分整个屏幕宽度,然后动态地addview()进去就好了。确实如此,如果只是为了实现功能的话,就是这么简单。可是别忘了,我们是在手机上进行开发,如果不停地往linearlayout里添加图片,程序很快就会oom。因此我们还需要一个合理的方案来对图片资源进行释放,这里仍然是准备使用lrucache算法,这个具体的在文后会专门讲,先知道是用这么回事~
下面我们就来开始实现吧,新建一个android项目,起名叫photowallfallsdemo,并选择4.0的api。
第一个要考虑的问题是,我们到哪儿去收集这些大小参差不齐的图片呢?这里我事先在百度上搜索了很多张风景图片,并且为了保证它们访问的稳定性,我将这些图片都上传到了我的csdn相册里,因此只要从这里下载图片就可以了。新建一个images类,将所有相册中图片的网址都配置进去,代码如下所示:

public class images { 
 
 public final static string[] imageurls = new string[] { 
   "http://img.my.csdn.net/uploads/201309/01/1378037235_3453.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037235_7476.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037235_9280.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037234_3539.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037234_6318.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037194_2965.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037193_1687.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037193_1286.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037192_8379.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037178_9374.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037177_1254.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037177_6203.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037152_6352.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037151_9565.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037151_7904.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037148_7104.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037129_8825.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037128_5291.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037128_3531.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037127_1085.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037095_7515.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037094_8001.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037093_7168.jpg", 
   "http://img.my.csdn.net/uploads/201309/01/1378037091_4950.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949643_6410.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949642_6939.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949630_4505.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949630_4593.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949629_7309.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949629_8247.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949615_1986.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949614_8482.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949614_3743.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949614_4199.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949599_3416.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949599_5269.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949598_7858.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949598_9982.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949578_2770.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949578_8744.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949577_5210.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949577_1998.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949482_8813.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949481_6577.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949480_4490.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949455_6792.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949455_6345.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949442_4553.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949441_8987.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949441_5454.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949454_6367.jpg", 
   "http://img.my.csdn.net/uploads/201308/31/1377949442_4562.jpg" }; 
} 

然后新建一个imageloader类,用于方便对图片进行管理,代码如下所示:

public class imageloader { 
 
 /** 
  * 图片缓存技术的核心类,用于缓存所有下载好的图片,在程序内存达到设定值时会将最少最近使用的图片移除掉。 
  */ 
 private static lrucache<string, bitmap> mmemorycache; 
 
 /** 
  * imageloader的实例。 
  */ 
 private static imageloader mimageloader; 
 
 private imageloader() { 
  // 获取应用程序最大可用内存 
  int maxmemory = (int) runtime.getruntime().maxmemory(); 
  int cachesize = maxmemory / 8; 
  // 设置图片缓存大小为程序最大可用内存的1/8 
  mmemorycache = new lrucache<string, bitmap>(cachesize) { 
   @override 
   protected int sizeof(string key, bitmap bitmap) { 
    return bitmap.getbytecount(); 
   } 
  }; 
 } 
 
 /** 
  * 获取imageloader的实例。 
  * 
  * @return imageloader的实例。 
  */ 
 public static imageloader getinstance() { 
  if (mimageloader == null) { 
   mimageloader = new imageloader(); 
  } 
  return mimageloader; 
 } 
 
 /** 
  * 将一张图片存储到lrucache中。 
  * 
  * @param key 
  *   lrucache的键,这里传入图片的url地址。 
  * @param bitmap 
  *   lrucache的键,这里传入从网络上下载的bitmap对象。 
  */ 
 public void addbitmaptomemorycache(string key, bitmap bitmap) { 
  if (getbitmapfrommemorycache(key) == null) { 
   mmemorycache.put(key, bitmap); 
  } 
 } 
 
 /** 
  * 从lrucache中获取一张图片,如果不存在就返回null。 
  * 
  * @param key 
  *   lrucache的键,这里传入图片的url地址。 
  * @return 对应传入键的bitmap对象,或者null。 
  */ 
 public bitmap getbitmapfrommemorycache(string key) { 
  return mmemorycache.get(key); 
 } 
 
 public static int calculateinsamplesize(bitmapfactory.options options, 
   int reqwidth) { 
  // 源图片的宽度 
  final int width = options.outwidth; 
  int insamplesize = 1; 
  if (width > reqwidth) { 
   // 计算出实际宽度和目标宽度的比率 
   final int widthratio = math.round((float) width / (float) reqwidth); 
   insamplesize = widthratio; 
  } 
  return insamplesize; 
 } 
 
 public static bitmap decodesampledbitmapfromresource(string pathname, 
   int reqwidth) { 
  // 第一次解析将injustdecodebounds设置为true,来获取图片大小 
  final bitmapfactory.options options = new bitmapfactory.options(); 
  options.injustdecodebounds = true; 
  bitmapfactory.decodefile(pathname, options); 
  // 调用上面定义的方法计算insamplesize值 
  options.insamplesize = calculateinsamplesize(options, reqwidth); 
  // 使用获取到的insamplesize值再次解析图片 
  options.injustdecodebounds = false; 
  return bitmapfactory.decodefile(pathname, options); 
 } 
 
} 

这里我们将imageloader类设成单例,并在构造函数中初始化了lrucache类,把它的最大缓存容量设为最大可用内存的1/8。然后又提供了其它几个方法可以操作lrucache,以及对图片进行压缩和读取。
接下来新建myscrollview继承自scrollview,代码如下所示:

public class myscrollview extends scrollview implements ontouchlistener { 
 
 /** 
  * 每页要加载的图片数量 
  */ 
 public static final int page_size = 15; 
 
 /** 
  * 记录当前已加载到第几页 
  */ 
 private int page; 
 
 /** 
  * 每一列的宽度 
  */ 
 private int columnwidth; 
 
 /** 
  * 当前第一列的高度 
  */ 
 private int firstcolumnheight; 
 
 /** 
  * 当前第二列的高度 
  */ 
 private int secondcolumnheight; 
 
 /** 
  * 当前第三列的高度 
  */ 
 private int thirdcolumnheight; 
 
 /** 
  * 是否已加载过一次layout,这里onlayout中的初始化只需加载一次 
  */ 
 private boolean loadonce; 
 
 /** 
  * 对图片进行管理的工具类 
  */ 
 private imageloader imageloader; 
 
 /** 
  * 第一列的布局 
  */ 
 private linearlayout firstcolumn; 
 
 /** 
  * 第二列的布局 
  */ 
 private linearlayout secondcolumn; 
 
 /** 
  * 第三列的布局 
  */ 
 private linearlayout thirdcolumn; 
 
 /** 
  * 记录所有正在下载或等待下载的任务。 
  */ 
 private static set<loadimagetask> taskcollection; 
 
 /** 
  * myscrollview下的直接子布局。 
  */ 
 private static view scrolllayout; 
 
 /** 
  * myscrollview布局的高度。 
  */ 
 private static int scrollviewheight; 
 
 /** 
  * 记录上垂直方向的滚动距离。 
  */ 
 private static int lastscrolly = -1; 
 
 /** 
  * 记录所有界面上的图片,用以可以随时控制对图片的释放。 
  */ 
 private list<imageview> imageviewlist = new arraylist<imageview>(); 
 
 /** 
  * 在handler中进行图片可见性检查的判断,以及加载更多图片的操作。 
  */ 
 private static handler handler = new handler() { 
 
  public void handlemessage(android.os.message msg) { 
   myscrollview myscrollview = (myscrollview) msg.obj; 
   int scrolly = myscrollview.getscrolly(); 
   // 如果当前的滚动位置和上次相同,表示已停止滚动 
   if (scrolly == lastscrolly) { 
    // 当滚动的最底部,并且当前没有正在下载的任务时,开始加载下一页的图片 
    if (scrollviewheight + scrolly >= scrolllayout.getheight() 
      && taskcollection.isempty()) { 
     myscrollview.loadmoreimages(); 
    } 
    myscrollview.checkvisibility(); 
   } else { 
    lastscrolly = scrolly; 
    message message = new message(); 
    message.obj = myscrollview; 
    // 5毫秒后再次对滚动位置进行判断 
    handler.sendmessagedelayed(message, 5); 
   } 
  }; 
 
 }; 
 
 /** 
  * myscrollview的构造函数。 
  * 
  * @param context 
  * @param attrs 
  */ 
 public myscrollview(context context, attributeset attrs) { 
  super(context, attrs); 
  imageloader = imageloader.getinstance(); 
  taskcollection = new hashset<loadimagetask>(); 
  setontouchlistener(this); 
 } 
 
 /** 
  * 进行一些关键性的初始化操作,获取myscrollview的高度,以及得到第一列的宽度值。并在这里开始加载第一页的图片。 
  */ 
 @override 
 protected void onlayout(boolean changed, int l, int t, int r, int b) { 
  super.onlayout(changed, l, t, r, b); 
  if (changed && !loadonce) { 
   scrollviewheight = getheight(); 
   scrolllayout = getchildat(0); 
   firstcolumn = (linearlayout) findviewbyid(r.id.first_column); 
   secondcolumn = (linearlayout) findviewbyid(r.id.second_column); 
   thirdcolumn = (linearlayout) findviewbyid(r.id.third_column); 
   columnwidth = firstcolumn.getwidth(); 
   loadonce = true; 
   loadmoreimages(); 
  } 
 } 
 
 /** 
  * 监听用户的触屏事件,如果用户手指离开屏幕则开始进行滚动检测。 
  */ 
 @override 
 public boolean ontouch(view v, motionevent event) { 
  if (event.getaction() == motionevent.action_up) { 
   message message = new message(); 
   message.obj = this; 
   handler.sendmessagedelayed(message, 5); 
  } 
  return false; 
 } 
 
 /** 
  * 开始加载下一页的图片,每张图片都会开启一个异步线程去下载。 
  */ 
 public void loadmoreimages() { 
  if (hassdcard()) { 
   int startindex = page * page_size; 
   int endindex = page * page_size + page_size; 
   if (startindex < images.imageurls.length) { 
    toast.maketext(getcontext(), "正在加载...", toast.length_short) 
      .show(); 
    if (endindex > images.imageurls.length) { 
     endindex = images.imageurls.length; 
    } 
    for (int i = startindex; i < endindex; i++) { 
     loadimagetask task = new loadimagetask(); 
     taskcollection.add(task); 
     task.execute(images.imageurls[i]); 
    } 
    page++; 
   } else { 
    toast.maketext(getcontext(), "已没有更多图片", toast.length_short) 
      .show(); 
   } 
  } else { 
   toast.maketext(getcontext(), "未发现sd卡", toast.length_short).show(); 
  } 
 } 
 
 /** 
  * 遍历imageviewlist中的每张图片,对图片的可见性进行检查,如果图片已经离开屏幕可见范围,则将图片替换成一张空图。 
  */ 
 public void checkvisibility() { 
  for (int i = 0; i < imageviewlist.size(); i++) { 
   imageview imageview = imageviewlist.get(i); 
   int bordertop = (integer) imageview.gettag(r.string.border_top); 
   int borderbottom = (integer) imageview 
     .gettag(r.string.border_bottom); 
   if (borderbottom > getscrolly() 
     && bordertop < getscrolly() + scrollviewheight) { 
    string imageurl = (string) imageview.gettag(r.string.image_url); 
    bitmap bitmap = imageloader.getbitmapfrommemorycache(imageurl); 
    if (bitmap != null) { 
     imageview.setimagebitmap(bitmap); 
    } else { 
     loadimagetask task = new loadimagetask(imageview); 
     task.execute(imageurl); 
    } 
   } else { 
    imageview.setimageresource(r.drawable.empty_photo); 
   } 
  } 
 } 
 
 /** 
  * 判断手机是否有sd卡。 
  * 
  * @return 有sd卡返回true,没有返回false。 
  */ 
 private boolean hassdcard() { 
  return environment.media_mounted.equals(environment 
    .getexternalstoragestate()); 
 } 
 
 /** 
  * 异步下载图片的任务。 
  * 
  * @author guolin 
  */ 
 class loadimagetask extends asynctask<string, void, bitmap> { 
 
  /** 
   * 图片的url地址 
   */ 
  private string mimageurl; 
 
  /** 
   * 可重复使用的imageview 
   */ 
  private imageview mimageview; 
 
  public loadimagetask() { 
  } 
 
  /** 
   * 将可重复使用的imageview传入 
   * 
   * @param imageview 
   */ 
  public loadimagetask(imageview imageview) { 
   mimageview = imageview; 
  } 
 
  @override 
  protected bitmap doinbackground(string... params) { 
   mimageurl = params[0]; 
   bitmap imagebitmap = imageloader 
     .getbitmapfrommemorycache(mimageurl); 
   if (imagebitmap == null) { 
    imagebitmap = loadimage(mimageurl); 
   } 
   return imagebitmap; 
  } 
 
  @override 
  protected void onpostexecute(bitmap bitmap) { 
   if (bitmap != null) { 
    double ratio = bitmap.getwidth() / (columnwidth * 1.0); 
    int scaledheight = (int) (bitmap.getheight() / ratio); 
    addimage(bitmap, columnwidth, scaledheight); 
   } 
   taskcollection.remove(this); 
  } 
 
  /** 
   * 根据传入的url,对图片进行加载。如果这张图片已经存在于sd卡中,则直接从sd卡里读取,否则就从网络上下载。 
   * 
   * @param imageurl 
   *   图片的url地址 
   * @return 加载到内存的图片。 
   */ 
  private bitmap loadimage(string imageurl) { 
   file imagefile = new file(getimagepath(imageurl)); 
   if (!imagefile.exists()) { 
    downloadimage(imageurl); 
   } 
   if (imageurl != null) { 
    bitmap bitmap = imageloader.decodesampledbitmapfromresource( 
      imagefile.getpath(), columnwidth); 
    if (bitmap != null) { 
     imageloader.addbitmaptomemorycache(imageurl, bitmap); 
     return bitmap; 
    } 
   } 
   return null; 
  } 
 
  /** 
   * 向imageview中添加一张图片 
   * 
   * @param bitmap 
   *   待添加的图片 
   * @param imagewidth 
   *   图片的宽度 
   * @param imageheight 
   *   图片的高度 
   */ 
  private void addimage(bitmap bitmap, int imagewidth, int imageheight) { 
   linearlayout.layoutparams params = new linearlayout.layoutparams( 
     imagewidth, imageheight); 
   if (mimageview != null) { 
    mimageview.setimagebitmap(bitmap); 
   } else { 
    imageview imageview = new imageview(getcontext()); 
    imageview.setlayoutparams(params); 
    imageview.setimagebitmap(bitmap); 
    imageview.setscaletype(scaletype.fit_xy); 
    imageview.setpadding(5, 5, 5, 5); 
    imageview.settag(r.string.image_url, mimageurl); 
    findcolumntoadd(imageview, imageheight).addview(imageview); 
    imageviewlist.add(imageview); 
   } 
  } 
 
  /** 
   * 找到此时应该添加图片的一列。原则就是对三列的高度进行判断,当前高度最小的一列就是应该添加的一列。 
   * 
   * @param imageview 
   * @param imageheight 
   * @return 应该添加图片的一列 
   */ 
  private linearlayout findcolumntoadd(imageview imageview, 
    int imageheight) { 
   if (firstcolumnheight <= secondcolumnheight) { 
    if (firstcolumnheight <= thirdcolumnheight) { 
     imageview.settag(r.string.border_top, firstcolumnheight); 
     firstcolumnheight += imageheight; 
     imageview.settag(r.string.border_bottom, firstcolumnheight); 
     return firstcolumn; 
    } 
    imageview.settag(r.string.border_top, thirdcolumnheight); 
    thirdcolumnheight += imageheight; 
    imageview.settag(r.string.border_bottom, thirdcolumnheight); 
    return thirdcolumn; 
   } else { 
    if (secondcolumnheight <= thirdcolumnheight) { 
     imageview.settag(r.string.border_top, secondcolumnheight); 
     secondcolumnheight += imageheight; 
     imageview 
       .settag(r.string.border_bottom, secondcolumnheight); 
     return secondcolumn; 
    } 
    imageview.settag(r.string.border_top, thirdcolumnheight); 
    thirdcolumnheight += imageheight; 
    imageview.settag(r.string.border_bottom, thirdcolumnheight); 
    return thirdcolumn; 
   } 
  } 
 
  /** 
   * 将图片下载到sd卡缓存起来。 
   * 
   * @param imageurl 
   *   图片的url地址。 
   */ 
  private void downloadimage(string imageurl) { 
   httpurlconnection con = null; 
   fileoutputstream fos = null; 
   bufferedoutputstream bos = null; 
   bufferedinputstream bis = null; 
   file imagefile = null; 
   try { 
    url url = new url(imageurl); 
    con = (httpurlconnection) url.openconnection(); 
    con.setconnecttimeout(5 * 1000); 
    con.setreadtimeout(15 * 1000); 
    con.setdoinput(true); 
    con.setdooutput(true); 
    bis = new bufferedinputstream(con.getinputstream()); 
    imagefile = new file(getimagepath(imageurl)); 
    fos = new fileoutputstream(imagefile); 
    bos = new bufferedoutputstream(fos); 
    byte[] b = new byte[1024]; 
    int length; 
    while ((length = bis.read(b)) != -1) { 
     bos.write(b, 0, length); 
     bos.flush(); 
    } 
   } catch (exception e) { 
    e.printstacktrace(); 
   } finally { 
    try { 
     if (bis != null) { 
      bis.close(); 
     } 
     if (bos != null) { 
      bos.close(); 
     } 
     if (con != null) { 
      con.disconnect(); 
     } 
    } catch (ioexception e) { 
     e.printstacktrace(); 
    } 
   } 
   if (imagefile != null) { 
    bitmap bitmap = imageloader.decodesampledbitmapfromresource( 
      imagefile.getpath(), columnwidth); 
    if (bitmap != null) { 
     imageloader.addbitmaptomemorycache(imageurl, bitmap); 
    } 
   } 
  } 
 
  /** 
   * 获取图片的本地存储路径。 
   * 
   * @param imageurl 
   *   图片的url地址。 
   * @return 图片的本地存储路径。 
   */ 
  private string getimagepath(string imageurl) { 
   int lastslashindex = imageurl.lastindexof("/"); 
   string imagename = imageurl.substring(lastslashindex + 1); 
   string imagedir = environment.getexternalstoragedirectory() 
     .getpath() + "/photowallfalls/"; 
   file file = new file(imagedir); 
   if (!file.exists()) { 
    file.mkdirs(); 
   } 
   string imagepath = imagedir + imagename; 
   return imagepath; 
  } 
 } 
 
} 

myscrollview是实现瀑布流照片墙的核心类,这里我来重点给大家介绍一下。首先它是继承自scrollview的,这样就允许用户可以通过滚动的方式来浏览更多的图片。这里提供了一个loadmoreimages()方法,是专门用于加载下一页的图片的,因此在onlayout()方法中我们要先调用一次这个方法,以初始化第一页的图片。然后在ontouch方法中每当监听到手指离开屏幕的事件,就会通过一个handler来对当前scrollview的滚动状态进行判断,如果发现已经滚动到了最底部,就会再次调用loadmoreimages()方法去加载下一页的图片。
那我们就要来看一看loadmoreimages()方法的内部细节了。在这个方法中,使用了一个循环来加载这一页中的每一张图片,每次都会开启一个loadimagetask,用于对图片进行异步加载。然后在loadimagetask中,首先会先检查一下这张图片是不是已经存在于sd卡中了,如果还没存在,就从网络上下载,然后把这张图片存放在lrucache中。接着将这张图按照一定的比例进行压缩,并找出当前高度最小的一列,把压缩后的图片添加进去就可以了。
另外,为了保证照片墙上的图片都能够合适地被回收,这里还加入了一个可见性检查的方法,即checkvisibility()方法。这个方法的核心思想就是检查目前照片墙上的所有图片,判断出哪些是可见的,哪些是不可见。然后将那些不可见的图片都替换成一张空图,这样就可以保证程序始终不会占用过高的内存。当这些图片又重新变为可见的时候,只需要再从lrucache中将这些图片重新取出即可。如果某张图片已经从lrucache中被移除了,就会开启一个loadimagetask,将这张图片重新加载到内存中。
然后打开或新建activity_main.xml,在里面设置好瀑布流的布局方式,如下所示:

<com.example.photowallfallsdemo.myscrollview xmlns:android="http://schemas.android.com/apk/res/android" 
 android:id="@+id/my_scroll_view" 
 android:layout_width="match_parent" 
 android:layout_height="match_parent" > 
 
 <linearlayout 
  android:layout_width="match_parent" 
  android:layout_height="wrap_content" 
  android:orientation="horizontal" > 
 
  <linearlayout 
   android:id="@+id/first_column" 
   android:layout_width="0dp" 
   android:layout_height="wrap_content" 
   android:layout_weight="1" 
   android:orientation="vertical" > 
  </linearlayout> 
 
  <linearlayout 
   android:id="@+id/second_column" 
   android:layout_width="0dp" 
   android:layout_height="wrap_content" 
   android:layout_weight="1" 
   android:orientation="vertical" > 
  </linearlayout> 
 
  <linearlayout 
   android:id="@+id/third_column" 
   android:layout_width="0dp" 
   android:layout_height="wrap_content" 
   android:layout_weight="1" 
   android:orientation="vertical" > 
  </linearlayout> 
 </linearlayout> 
 
</com.example.photowallfallsdemo.myscrollview>

 
可以看到,这里我们使用了刚才编写好的myscrollview作为根布局,然后在里面放入了一个直接子布局linearlayout用于统计当前滑动布局的高度,然后在这个布局下又添加了三个等宽的linearlayout分别作为第一列、第二列和第三列的布局,这样在myscrollview中就可以动态地向这三个linearlayout里添加图片了。
最后,由于我们使用到了网络和sd卡存储的功能,因此还需要在androidmanifest.xml中添加以下权限:

<uses-permission android:name="android.permission.write_external_storage" /> 
<uses-permission android:name="android.permission.internet" /> 

这样我们所有的编码工作就已经完成了,现在可以尝试运行一下,效果如下图所示:

201648235542999.gif (235×418)

lrucache图片缓存技术
在你应用程序的ui界面加载一张图片是一件很简单的事情,但是当你需要在界面上加载一大堆图片的时候,情况就变得复杂起来。在很多情况下,(比如使用listview, gridview 或者 viewpager 这样的组件),屏幕上显示的图片可以通过滑动屏幕等事件不断地增加,最终导致oom。
为了保证内存的使用始终维持在一个合理的范围,通常会把被移除屏幕的图片进行回收处理。此时垃圾回收器也会认为你不再持有这些图片的引用,从而对这些图片进行gc操作。用这种思路来解决问题是非常好的,可是为了能让程序快速运行,在界面上迅速地加载图片,你又必须要考虑到某些图片被回收之后,用户又将它重新滑入屏幕这种情况。这时重新去加载一遍刚刚加载过的图片无疑是性能的瓶颈,你需要想办法去避免这个情况的发生。
这个时候,使用内存缓存技术可以很好的解决这个问题,它可以让组件快速地重新加载和处理图片。下面我们就来看一看如何使用内存缓存技术来对图片进行缓存,从而让你的应用程序在加载很多图片的时候可以提高响应速度和流畅性。
内存缓存技术对那些大量占用应用程序宝贵内存的图片提供了快速访问的方法。其中最核心的类是lrucache (此类在android-support-v4的包中提供) 。这个类非常适合用来缓存图片,它的主要算法原理是把最近使用的对象用强引用存储在 linkedhashmap 中,并且把最近最少使用的对象在缓存值达到预设定值之前从内存中移除。
在过去,我们经常会使用一种非常流行的内存缓存技术的实现,即软引用或弱引用 (softreference or weakreference)。但是现在已经不再推荐使用这种方式了,因为从 android 2.3 (api level 9)开始,垃圾回收器会更倾向于回收持有软引用或弱引用的对象,这让软引用和弱引用变得不再可靠。另外,android 3.0 (api level 11)中,图片的数据会存储在本地的内存当中,因而无法用一种可预见的方式将其释放,这就有潜在的风险造成应用程序的内存溢出并崩溃。
为了能够选择一个合适的缓存大小给lrucache, 有以下多个因素应该放入考虑范围内,例如:
你的设备可以为每个应用程序分配多大的内存?
设备屏幕上一次最多能显示多少张图片?有多少图片需要进行预加载,因为有可能很快也会显示在屏幕上?
你的设备的屏幕大小和分辨率分别是多少?一个超高分辨率的设备(例如 galaxy nexus) 比起一个较低分辨率的设备(例如 nexus s),在持有相同数量图片的时候,需要更大的缓存空间。
图片的尺寸和大小,还有每张图片会占据多少内存空间。
图片被访问的频率有多高?会不会有一些图片的访问频率比其它图片要高?如果有的话,你也许应该让一些图片常驻在内存当中,或者使用多个lrucache 对象来区分不同组的图片。
你能维持好数量和质量之间的平衡吗?有些时候,存储多个低像素的图片,而在后台去开线程加载高像素的图片会更加的有效。
并没有一个指定的缓存大小可以满足所有的应用程序,这是由你决定的。你应该去分析程序内存的使用情况,然后制定出一个合适的解决方案。一个太小的缓存空间,有可能造成图片频繁地被释放和重新加载,这并没有好处。而一个太大的缓存空间,则有可能还是会引起 java.lang.outofmemory 的异常。
下面是一个使用 lrucache 来缓存图片的例子:

private lrucache<string, bitmap> mmemorycache; 
 
@override 
protected void oncreate(bundle savedinstancestate) { 
  // 获取到可用内存的最大值,使用内存超出这个值会引起outofmemory异常。 
  // lrucache通过构造函数传入缓存值,以kb为单位。 
  int maxmemory = (int) (runtime.getruntime().maxmemory() / 1024); 
  // 使用最大可用内存值的1/8作为缓存的大小。 
  int cachesize = maxmemory / 8; 
  mmemorycache = new lrucache<string, bitmap>(cachesize) { 
    @override 
    protected int sizeof(string key, bitmap bitmap) { 
      // 重写此方法来衡量每张图片的大小,默认返回图片数量。 
      return bitmap.getbytecount() / 1024; 
    } 
  }; 
} 
 
public void addbitmaptomemorycache(string key, bitmap bitmap) { 
  if (getbitmapfrommemcache(key) == null) { 
    mmemorycache.put(key, bitmap); 
  } 
} 
 
public bitmap getbitmapfrommemcache(string key) { 
  return mmemorycache.get(key); 
} 

在这个例子当中,使用了系统分配给应用程序的八分之一内存来作为缓存大小。在中高配置的手机当中,这大概会有4兆(32/8)的缓存空间。一个全屏幕的 gridview 使用4张 800x480分辨率的图片来填充,则大概会占用1.5兆的空间(800*480*4)。因此,这个缓存大小可以存储2.5页的图片。
当向 imageview 中加载一张图片时,首先会在 lrucache 的缓存中进行检查。如果找到了相应的键值,则会立刻更新imageview ,否则开启一个后台线程来加载这张图片。

public void loadbitmap(int resid, imageview imageview) { 
  final string imagekey = string.valueof(resid); 
  final bitmap bitmap = getbitmapfrommemcache(imagekey); 
  if (bitmap != null) { 
    imageview.setimagebitmap(bitmap); 
  } else { 
    imageview.setimageresource(r.drawable.image_placeholder); 
    bitmapworkertask task = new bitmapworkertask(imageview); 
    task.execute(resid); 
  } 
} 

bitmapworkertask 还要把新加载的图片的键值对放到缓存中。

class bitmapworkertask extends asynctask<integer, void, bitmap> { 
  // 在后台加载图片。 
  @override 
  protected bitmap doinbackground(integer... params) { 
    final bitmap bitmap = decodesampledbitmapfromresource( 
        getresources(), params[0], 100, 100); 
    addbitmaptomemorycache(string.valueof(params[0]), bitmap); 
    return bitmap; 
  } 
} 

掌握了以上两种方法,不管是要在程序中加载超大图片,还是要加载大量图片,都不用担心oom的问题了!

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网