Android UI 之WaterFall瀑布流效果 [複製連接]

所謂瀑布流效果,簡單說就是寬度相同可是高度不一樣的一大堆圖片,分紅幾列,而後像水流同樣向下排列,並隨着用戶的上下滑動自動加載更多的圖片內容。php

    語言描述比較抽象,具體效果看下面的截圖:java

        

    其實這個效果在web上應用的還蠻多的,在android上也有一些應用有用到。由於看起來良莠不齊,因此比較有新鮮感,不像傳統的九宮格那樣千篇一概。android

    網絡上相關的文章也有幾篇,可是整理後發現要麼忽略了OOM的處理,要麼代碼的邏輯相對來講有一點混亂,滑動效果也有一點卡頓。web

    因此後來本身乾脆換了一下思路,從新實現了這樣一個瀑布流效果。目前作的測試很少,可是加載幾千張圖片尚未出現過OOM的狀況,滑動也比較流暢。算法


    下面大致講解一下實現思路。canvas

    要想比較好的實現這個效果主要有兩個重點:網絡

    一是在用戶滑動到底部的時候加載下一組圖片內容的處理。app

    二是當加載圖片比較多的狀況下,對圖片進行回收,防止OOM的處理。dom

    對於第一點,主要是加載時機的判斷以及加載內容的異步處理。這一部分其實理解起來仍是比較容易,具體能夠參見下面給出的源碼。異步

    對於第二點,在進行回收的時候,咱們的總體思路是以用戶當前看到的這一個屏幕爲基準,向上兩屏以及向下兩屏一共有5屏的內容,超出這5屏範圍的bitmap將被回收。

    在向上滾動的時候,將回收超過下方兩屏範圍的bitmap,並重載進入上方兩屏的bitmap。

    在向下滾動的時候,將回收超過上方兩屏範圍的bitmap,並重載進入下方兩屏的bitmap。

    具體的實現思路仍是參見源碼,我有給出比較詳細的註釋。

先來看一下項目的結構:


WaterFall.java

  1. package com.carrey.waterfall.waterfall;

  2. import java.io.IOException;
  3. import java.lang.ref.WeakReference;
  4. import java.util.ArrayList;
  5. import java.util.Random;

  6. import android.content.Context;
  7. import android.graphics.Color;
  8. import android.os.Handler;
  9. import android.os.Message;
  10. import android.util.AttributeSet;
  11. import android.view.MotionEvent;
  12. import android.widget.LinearLayout;
  13. import android.widget.ScrollView;
  14. /**
  15. * 瀑布流
  16. * 某些參數作了固定設置,若是想擴展功能,可自行修改
  17. * @author carrey
  18. *
  19. */
  20. public class WaterFall extends ScrollView {
  21.         
  22.         /** 延遲發送message的handler */
  23.         private DelayHandler delayHandler;
  24.         /** 添加單元到瀑布流中的Handler */
  25.         private AddItemHandler addItemHandler;
  26.         
  27.         /** ScrollView直接包裹的LinearLayout */
  28.         private LinearLayout containerLayout;
  29.         /** 存放全部的列Layout */
  30.         private ArrayList<LinearLayout> colLayoutArray;
  31.         
  32.         /** 當前所處的頁面(已經加載了幾回) */
  33.         private int currentPage;
  34.         
  35.         /** 存儲每一列中向上方向的未被回收bitmap的單元的最小行號 */
  36.         private int[] currentTopLineIndex;
  37.         /** 存儲每一列中向下方向的未被回收bitmap的單元的最大行號 */
  38.         private int[] currentBomLineIndex;
  39.         /** 存儲每一列中已經加載的最下方的單元的行號 */
  40.         private int[] bomLineIndex;
  41.         /** 存儲每一列的高度 */
  42.         private int[] colHeight;
  43.         
  44.         /** 全部的圖片資源路徑 */
  45.         private String[] imageFilePaths;
  46.         
  47.         /** 瀑布流顯示的列數 */
  48.         private int colCount;
  49.         /** 瀑布流每一次加載的單元數量 */
  50.         private int pageCount;
  51.         /** 瀑布流容納量 */
  52.         private int capacity;
  53.         
  54.         private Random random;
  55.         
  56.         /** 列的寬度 */
  57.         private int colWidth;
  58.         
  59.         private boolean isFirstPage;

  60.         public WaterFall(Context context, AttributeSet attrs, int defStyle) {
  61.                 super(context, attrs, defStyle);
  62.                 init();
  63.         }

  64.         public WaterFall(Context context, AttributeSet attrs) {
  65.                 super(context, attrs);
  66.                 init();
  67.         }

  68.         public WaterFall(Context context) {
  69.                 super(context);
  70.                 init();
  71.         }
  72.         
  73.         /** 基本初始化工做 */
  74.         private void init() {
  75.                 delayHandler = new DelayHandler(this);
  76.                 addItemHandler = new AddItemHandler(this);
  77.                 colCount = 4;//默認狀況下是4列
  78.                 pageCount = 30;//默認每次加載30個瀑布流單元
  79.                 capacity = 10000;//默認容納10000張圖
  80.                 random = new Random();
  81.                 colWidth = getResources().getDisplayMetrics().widthPixels / colCount;
  82.                 
  83.                 colHeight = new int[colCount];
  84.                 currentTopLineIndex = new int[colCount];
  85.                 currentBomLineIndex = new int[colCount];
  86.                 bomLineIndex = new int[colCount];
  87.                 colLayoutArray = new ArrayList<LinearLayout>();
  88.         }
  89.         
  90.         /**
  91.          * 在外部調用 第一次裝載頁面 必須調用
  92.          */
  93.         public void setup() {
  94.                 containerLayout = new LinearLayout(getContext());
  95.                 containerLayout.setBackgroundColor(Color.WHITE);
  96.                 LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
  97.                                 LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
  98.                 addView(containerLayout, layoutParams);
  99.                 
  100.                 for (int i = 0; i < colCount; i++) {
  101.                         LinearLayout colLayout = new LinearLayout(getContext());
  102.                         LinearLayout.LayoutParams colLayoutParams = new LinearLayout.LayoutParams(
  103.                                         colWidth, LinearLayout.LayoutParams.WRAP_CONTENT);
  104.                         colLayout.setPadding(2, 2, 2, 2);
  105.                         colLayout.setOrientation(LinearLayout.VERTICAL);
  106.                         
  107.                         containerLayout.addView(colLayout, colLayoutParams);
  108.                         colLayoutArray.add(colLayout);
  109.                 }
  110.                 
  111.                 try {
  112.                         imageFilePaths = getContext().getAssets().list("images");
  113.                 } catch (IOException e) {
  114.                         e.printStackTrace();
  115.                 }
  116.                 //添加第一頁
  117.                 addNextPageContent(true);
  118.         }

  119.         @Override
  120.         public boolean onTouchEvent(MotionEvent ev) {
  121.                 switch (ev.getAction()) {
  122.                 case MotionEvent.ACTION_DOWN:
  123.                         break;
  124.                 case MotionEvent.ACTION_UP:
  125.                         //手指離開屏幕的時候向DelayHandler延時發送一個信息,而後DelayHandler
  126.                         //屆時來判斷當前的滑動位置,進行不一樣的處理。
  127.                         delayHandler.sendMessageDelayed(delayHandler.obtainMessage(), 200);
  128.                         break;
  129.                 }
  130.                 return super.onTouchEvent(ev);
  131.         }
  132.         
  133.         @Override
  134.         protected void onScrollChanged(int l, int t, int oldl, int oldt) {
  135.                 //在滾動過程當中,回收滾動了很遠的bitmap,防止OOM
  136.                 /*---回收算法說明:
  137.                  * 回收的總體思路是:
  138.                  * 咱們只保持當前手機顯示的這一屏以及上方兩屏和下方兩屏 一共5屏內容的Bitmap,
  139.                  * 超出這個範圍的單元Bitmap都被回收。
  140.                  * 這其中又包括了一種狀況就是以前回收過的單元的從新加載。
  141.                  * 詳細的講解:
  142.                  * 向下滾動的時候:回收超過上方兩屏的單元Bitmap,重載進入下方兩屏之內Bitmap
  143.                  * 向上滾動的時候:回收超過下方兩屏的單元bitmao,重載進入上方兩屏之內bitmap
  144.                  * ---*/
  145.                 int viewHeight = getHeight();
  146.                 if (t > oldt) {//向下滾動
  147.                         if (t > 2 * viewHeight) {
  148.                                 for (int i = 0; i < colCount; i++) {
  149.                                         LinearLayout colLayout = colLayoutArray.get(i);
  150.                                         //回收上方超過兩屏bitmap
  151.                                         FlowingView topItem = (FlowingView) colLayout.getChildAt(currentTopLineIndex[i]);
  152.                                         if (topItem.getFootHeight() < t - 2 * viewHeight) {
  153.                                                 topItem.recycle();
  154.                                                 currentTopLineIndex[i] ++;
  155.                                         }
  156.                                         //重載下方進入(+1)兩屏之內bitmap
  157.                                         FlowingView bomItem = (FlowingView) colLayout.getChildAt(Math.min(currentBomLineIndex[i] + 1, bomLineIndex[i]));
  158.                                         if (bomItem.getFootHeight() <= t + 3 * viewHeight) {
  159.                                                 bomItem.reload();
  160.                                                 currentBomLineIndex[i] = Math.min(currentBomLineIndex[i] + 1, bomLineIndex[i]);
  161.                                         }
  162.                                 }
  163.                         }
  164.                 } else {//向上滾動
  165.                         for (int i = 0; i < colCount; i++) {
  166.                                 LinearLayout colLayout = colLayoutArray.get(i);
  167.                                 //回收下方超過兩屏bitmap
  168.                                 FlowingView bomItem = (FlowingView) colLayout.getChildAt(currentBomLineIndex[i]);
  169.                                 if (bomItem.getFootHeight() > t + 3 * viewHeight) {
  170.                                         bomItem.recycle();
  171.                                         currentBomLineIndex[i] --;
  172.                                 }
  173.                                 //重載上方進入(-1)兩屏之內bitmap
  174.                                 FlowingView topItem = (FlowingView) colLayout.getChildAt(Math.max(currentTopLineIndex[i] - 1, 0));
  175.                                 if (topItem.getFootHeight() >= t - 2 * viewHeight) {
  176.                                         topItem.reload();
  177.                                         currentTopLineIndex[i] = Math.max(currentTopLineIndex[i] - 1, 0);
  178.                                 }
  179.                         }
  180.                 }
  181.                 super.onScrollChanged(l, t, oldl, oldt);
  182.         }
  183.         
  184.         /**
  185.          * 這裏之因此要用一個Handler,是爲了使用他的延遲發送message的函數
  186.          * 延遲的效果在於,若是用戶快速滑動,手指很早離開屏幕,而後滑動到了底部的時候,
  187.          * 由於信息稍後發送,在手指離開屏幕到滑動到底部的這個時間差內,依然可以加載圖片
  188.          * @author carrey
  189.          *
  190.          */
  191.         private static class DelayHandler extends Handler {
  192.                 private WeakReference<WaterFall> waterFallWR;
  193.                 private WaterFall waterFall;
  194.                 public DelayHandler(WaterFall waterFall) {
  195.                         waterFallWR = new WeakReference<WaterFall>(waterFall);
  196.                         this.waterFall = waterFallWR.get();
  197.                 }
  198.                 
  199.                 @Override
  200.                 public void handleMessage(Message msg) {
  201.                         //判斷當前滑動到的位置,進行不一樣的處理
  202.                         if (waterFall.getScrollY() + waterFall.getHeight() >= 
  203.                                         waterFall.getMaxColHeight() - 20) {
  204.                                 //滑動到底部,添加下一頁內容
  205.                                 waterFall.addNextPageContent(false);
  206.                         } else if (waterFall.getScrollY() == 0) {
  207.                                 //滑動到了頂部
  208.                         } else {
  209.                                 //滑動在中間位置
  210.                         }
  211.                         super.handleMessage(msg);
  212.                 }
  213.         }
  214.         
  215.         /**
  216.          * 添加單元到瀑布流中的Handler
  217.          * @author carrey
  218.          *
  219.          */
  220.         private static class AddItemHandler extends Handler {
  221.                 private WeakReference<WaterFall> waterFallWR;
  222.                 private WaterFall waterFall;
  223.                 public AddItemHandler(WaterFall waterFall) {
  224.                         waterFallWR = new WeakReference<WaterFall>(waterFall);
  225.                         this.waterFall = waterFallWR.get();
  226.                 }
  227.                 @Override
  228.                 public void handleMessage(Message msg) {
  229.                         switch (msg.what) {
  230.                         case 0x00:
  231.                                 FlowingView flowingView = (FlowingView)msg.obj;
  232.                                 waterFall.addItem(flowingView);
  233.                                 break;
  234.                         }
  235.                         super.handleMessage(msg);
  236.                 }
  237.         }
  238.         /**
  239.          * 添加單元到瀑布流中
  240.          * @param flowingView
  241.          */
  242.         private void addItem(FlowingView flowingView) {
  243.                 int minHeightCol = getMinHeightColIndex();
  244.                 colLayoutArray.get(minHeightCol).addView(flowingView);
  245.                 colHeight[minHeightCol] += flowingView.getViewHeight();
  246.                 flowingView.setFootHeight(colHeight[minHeightCol]);
  247.                 
  248.                 if (!isFirstPage) {
  249.                         bomLineIndex[minHeightCol] ++;
  250.                         currentBomLineIndex[minHeightCol] ++;
  251.                 }
  252.         }
  253.         
  254.         /**
  255.          * 添加下一個頁面的內容
  256.          */
  257.         private void addNextPageContent(boolean isFirstPage) {
  258.                 this.isFirstPage = isFirstPage;
  259.                 
  260.                 //添加下一個頁面的pageCount個單元內容
  261.                 for (int i = pageCount * currentPage; 
  262.                                 i < pageCount * (currentPage + 1) && i < capacity; i++) {
  263.                         new Thread(new PrepareFlowingViewRunnable(i)).run();
  264.                 }
  265.                 currentPage ++;
  266.         }
  267.         
  268.         /**
  269.          * 異步加載要添加的FlowingView
  270.          * @author carrey
  271.          *
  272.          */
  273.         private class PrepareFlowingViewRunnable implements Runnable {
  274.                 private int id;
  275.                 public PrepareFlowingViewRunnable (int id) {
  276.                         this.id = id;
  277.                 }
  278.                 
  279.                 @Override
  280.                 public void run() {
  281.                         FlowingView flowingView = new FlowingView(getContext(), id, colWidth);
  282.                         String imageFilePath = "images/" + imageFilePaths[random.nextInt(imageFilePaths.length)];
  283.                         flowingView.setImageFilePath(imageFilePath);
  284.                         flowingView.loadImage();
  285.                         addItemHandler.sendMessage(addItemHandler.obtainMessage(0x00, flowingView));
  286.                 }
  287.                 
  288.         }
  289.         
  290.         /**
  291.          * 得到全部列中的最大高度
  292.          * @return
  293.          */
  294.         private int getMaxColHeight() {
  295.                 int maxHeight = colHeight[0];
  296.                 for (int i = 1; i < colHeight.length; i++) {
  297.                         if (colHeight[i] > maxHeight)
  298.                                 maxHeight = colHeight[i];
  299.                 }
  300.                 return maxHeight;
  301.         }
  302.         
  303.         /**
  304.          * 得到目前高度最小的列的索引
  305.          * @return
  306.          */
  307.         private int getMinHeightColIndex() {
  308.                 int index = 0;
  309.                 for (int i = 1; i < colHeight.length; i++) {
  310.                         if (colHeight[i] < colHeight[index])
  311.                                 index = i;
  312.                 }
  313.                 return index;
  314.         }
  315. }
複製代碼
FlowingView.java

  1. package com.carrey.waterfall.waterfall;

  2. import java.io.IOException;
  3. import java.io.InputStream;

  4. import android.content.Context;
  5. import android.graphics.Bitmap;
  6. import android.graphics.BitmapFactory;
  7. import android.graphics.Canvas;
  8. import android.graphics.Color;
  9. import android.graphics.Paint;
  10. import android.graphics.Rect;
  11. import android.view.View;
  12. import android.widget.Toast;
  13. /**
  14. * 瀑布流中流動的單元
  15. * @author carrey
  16. *
  17. */
  18. public class FlowingView extends View implements View.OnClickListener, View.OnLongClickListener {
  19.         
  20.         /** 單元的編號,在整個瀑布流中是惟一的,能夠用來標識身份 */
  21.         private int index;
  22.         
  23.         /** 單元中要顯示的圖片Bitmap */
  24.         private Bitmap imageBmp;
  25.         /** 圖像文件的路徑 */
  26.         private String imageFilePath;
  27.         /** 單元的寬度,也是圖像的寬度 */
  28.         private int width;
  29.         /** 單元的高度,也是圖像的高度 */
  30.         private int height;
  31.         
  32.         /** 畫筆 */
  33.         private Paint paint;
  34.         /** 圖像繪製區域 */
  35.         private Rect rect;
  36.         
  37.         /** 這個單元的底部到它所在列的頂部之間的距離 */
  38.         private int footHeight;
  39.         
  40.         public FlowingView(Context context, int index, int width) {
  41.                 super(context);
  42.                 this.index = index;
  43.                 this.width = width;
  44.                 init();
  45.         }
  46.         
  47.         /**
  48.          * 基本初始化工做
  49.          */
  50.         private void init() {
  51.                 setOnClickListener(this);
  52.                 setOnLongClickListener(this);
  53.                 paint = new Paint();
  54.                 paint.setAntiAlias(true);
  55.         }
  56.         
  57.         @Override
  58.         protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  59.                 setMeasuredDimension(width, height);
  60.         }
  61.         
  62.         @Override
  63.         protected void onDraw(Canvas canvas) {
  64.                 //繪製圖像
  65.                 canvas.drawColor(Color.WHITE);
  66.                 if (imageBmp != null && rect != null) {
  67.                         canvas.drawBitmap(imageBmp, null, rect, paint);
  68.                 }
  69.                 super.onDraw(canvas);
  70.         }
  71.         
  72.         /**
  73.          * 被WaterFall調用異步加載圖片數據
  74.          */
  75.         public void loadImage() {
  76.                 InputStream inStream = null;
  77.                 try {
  78.                         inStream = getContext().getAssets().open(imageFilePath);
  79.                         imageBmp = BitmapFactory.decodeStream(inStream);
  80.                         inStream.close();
  81.                         inStream = null;
  82.                 } catch (IOException e) {
  83.                         e.printStackTrace();
  84.                 }
  85.                 if (imageBmp != null) {
  86.                         int bmpWidth = imageBmp.getWidth();
  87.                         int bmpHeight = imageBmp.getHeight();
  88.                         height = (int) (bmpHeight * width / bmpWidth);
  89.                         rect = new Rect(0, 0, width, height);
  90.                 }
  91.         }
  92.         
  93.         /**
  94.          * 從新加載回收了的Bitmap
  95.          */
  96.         public void reload() {
  97.                 if (imageBmp == null) {
  98.                         new Thread(new Runnable() {
  99.                                 
  100.                                 @Override
  101.                                 public void run() {
  102.                                         InputStream inStream = null;
  103.                                         try {
  104.                                                 inStream = getContext().getAssets().open(imageFilePath);
  105.                                                 imageBmp = BitmapFactory.decodeStream(inStream);
  106.                                                 inStream.close();
  107.                                                 inStream = null;
  108.                                                 postInvalidate();
  109.                                         } catch (IOException e) {
  110.                                                 e.printStackTrace();
  111.                                         }
  112.                                 }
  113.                         }).start();
  114.                 }
  115.         }
  116.         
  117.         /**
  118.          * 防止OOM進行回收
  119.          */
  120.         public void recycle() {
  121.                 if (imageBmp == null || imageBmp.isRecycled()) 
  122.                         return;
  123.                 new Thread(new Runnable() {
  124.                         
  125.                         @Override
  126.                         public void run() {
  127.                                 imageBmp.recycle();
  128.                                 imageBmp = null;
  129.                                 postInvalidate();
  130.                         }
  131.                 }).start();
  132.         }
  133.         
  134.         @Override
  135.         public boolean onLongClick(View v) {
  136.                 Toast.makeText(getContext(), "long click : " + index, Toast.LENGTH_SHORT).show();
  137.                 return true;
  138.         }

  139.         @Override
  140.         public void onClick(View v) {
  141.                 Toast.makeText(getContext(), "click : " + index, Toast.LENGTH_SHORT).show();
  142.         }

  143.         /**
  144.          * 獲取單元的高度
  145.          * @return
  146.          */
  147.         public int getViewHeight() {
  148.                 return height;
  149.         }
  150.         /**
  151.          * 設置圖片路徑
  152.          * @param imageFilePath
  153.          */
  154.         public void setImageFilePath(String imageFilePath) {
  155.                 this.imageFilePath = imageFilePath;
  156.         }

  157.         public Bitmap getImageBmp() {
  158.                 return imageBmp;
  159.         }

  160.         public void setImageBmp(Bitmap imageBmp) {
  161.                 this.imageBmp = imageBmp;
  162.         }

  163.         public int getFootHeight() {
  164.                 return footHeight;
  165.         }

  166.         public void setFootHeight(int footHeight) {
  167.                 this.footHeight = footHeight;
  168.         }
  169. }
複製代碼
MainActivity.java

  1. package com.carrey.waterfall;

  2. import com.carrey.waterfall.waterfall.WaterFall;

  3. import android.os.Bundle;
  4. import android.app.Activity;

  5. public class MainActivity extends Activity {

  6.         @Override
  7.         protected void onCreate(Bundle savedInstanceState) {
  8.                 super.onCreate(savedInstanceState);
  9.                 setContentView(R.layout.activity_main);
  10.                 
  11.                 WaterFall waterFall = (WaterFall) findViewById(R.id.waterfall);
  12.                 waterFall.setup();
  13.         }

  14. }
複製代碼
activity_main.xml

  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=".MainActivity" >

  6.     <com.carrey.waterfall.waterfall.WaterFall 
  7.         android:id="@+id/waterfall"
  8.         android:layout_width="match_parent"
  9.         android:layout_height="match_parent"/>

  10. </RelativeLayout>
複製代碼
 WaterFall.rar (6.8 MB, 下載次數: 1082) 


相關文章
相關標籤/搜索