Android Waterfall Stream to resolve Oom

Source: Internet
Author: User

This is an Android waterfall streaming implementation demo.

Waterfall flow My implementation is to define three linearlayout, and then to the inside AddView (), if more will appear oom exception, so did some processing.

1.lrucache Cache

2. Display only the picture of the current screen

3. Do not load the picture during sliding

4. Large map zoom into small image


Look directly at the code:

Photofallscrollview.java the main class custom ScrollView.

Package Com.pangzaifei.falls;import Java.io.bufferedinputstream;import Java.io.bufferedoutputstream;import Java.io.file;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.InputStream;import Java.net.httpurlconnection;import Java.net.url;import Java.util.arraylist;import Java.util.HashSet;import Java.util.list;import Java.util.set;import Android.content.context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.os.asynctask;import Android.os.environment;import Android.os.handler;import Android.os.message;import Android.util.attributeset;import android.view.MotionEvent; Import Android.view.view;import Android.view.view.ontouchlistener;import Android.widget.imageview;import Android.widget.imageview.scaletype;import Android.widget.linearlayout;import Android.widget.ScrollView;import android.widget.toast;/** * Waterfall Flow class * * Principle: 1: Create 3 LinearLayout, set their width, compress the obtained picture into the same width as 3 linearlayout, * Then judging by the height of the 3 linearlayout, add bitmap to which LinearLayout *2: Page turn processing, according to the position of the gesture lifted and the end of the swipe to page * * @author PANGZF * @date July 15, 2014 morning 10:33:05 */public class Photofallscrollview extends    ScrollView implements Ontouchlistener {/** * pages * */private static int page;    /** * How many sheets per page */private static final int page_size = 8;    Private Context Mcontext;    /** * Data Source picture */Private Images mimagesthoumb;    /** * Task Request Collection */private set<downloadtask> mtasks;    Boolean isfirstentr = true;    Private LinearLayout Mfirstcolumn;    Private LinearLayout Msecondcolumn;    Private LinearLayout Mthirdcolumn;    private int mfirstcolumnheight;    private int msecondcolumnheight;    private int mthirdcolumnheight;    private int mclolumnwidth;    Private long mdelay = 5;    /** * Last position of the last swipe */private static int lastscrolly =-1;    /** * has the layout been loaded once, where initialization in onlayout only needs to be loaded once */private Boolean loadonce; /** * Store Picture Collection */private list<imageview> mimageviewlist = new ArraylisT<imageview> ();        Public Photofallscrollview (context context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle);        This.mcontext = context;    Init ();        } public Photofallscrollview (context context, AttributeSet Attrs) {Super (context, attrs);        This.mcontext = context;    Init ();        } public Photofallscrollview (context context) {super (context);        This.mcontext = context;    Init ();        }/** * Initialize */private void init () {mimagesthoumb = Images.getinstance ();        Mtasks = new hashset<downloadtask> ();    Setontouchlistener (this);  } @Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {super.onlayout (changed, L,        T, R, b);            First entry on load the first page of the picture if (changed &&!loadonce) {mscrollviewheight = This.getheight ();            Mscrolllayout = This.getchildat (0); Mfirstcolumn = (linearlayout) findviewbYid (R.id.first_column);            Msecondcolumn = (linearlayout) Findviewbyid (R.id.second_column);            Mthirdcolumn = (linearlayout) Findviewbyid (R.id.third_column);            Mclolumnwidth = Mfirstcolumn.getwidth ();            Loadonce = true;        Loadmoreimages ();            }}/** * Load picture */private void loadmoreimages () {if (Hashsdcard ()) {//Load picture based on number of pages            int startIndex = page * page_size;            int endIndex = page * page_size + page_size;  if (StartIndex < mImagesThoumb.imageThumbs.length) {if (EndIndex > MImagesThoumb.imageThumbs.length)                {endIndex = MImagesThoumb.imageThumbs.length; } for (int i = StartIndex; i < EndIndex; i++) {String IMAGEURL = Mimagesthoumb.image                    Thumbs[i].tostring (); if (IMAGEURL! = NULL &&! "".           Equals (IMAGEURL)) {downloaddata (IMAGEURL);         }} page++;            } else {Toast.maketext (Mcontext, "No More Pictures", 0). Show ();        }} else {Toast.maketext (Mcontext, "no SDcard", 0). Show (); }}/** * Download * * @param imageUrl */private void Downloaddata (String imageUrl) {DownLoad        Task task = new Downloadtask ();        Mtasks.add (Task);    Task.execute (IMAGEURL);        } public class Downloadtask extends Asynctask<string, string, bitmap> {private String mimageurl; @Override protected Bitmap doinbackground (String ... params) {try {Mimageurl = params[0]                ;                Bitmap bitmapfrommemory = mimagesthoumb. Getmemorycache (Mimageurl);                if (bitmapfrommemory! = null) {return bitmapfrommemory;          } if (Hashsdcard ()) {Bitmap Bitmap = LoadImage (Mimageurl);          return bitmap;                } else {Toast.maketext (Mcontext, "no sdcard, unable to get picture", 0). Show ();            }} catch (Exception e) {e.printstacktrace ();        } return null;            } @Override protected void OnPostExecute (Bitmap Bitmap) {super.onpostexecute (BITMAP); Show picture if (bitmap! = null) {//1. Zoom picture//2. New ImageView//3. Find                Required linerlayout Add imageview float width = bitmap.getwidth ();                FLOAT radio = Width/mfirstcolumn.getwidth ();                float ScaleHeight = Bitmap.getheight ()/radio;            AddImage (Bitmap, Mfirstcolumn.getwidth (), scaleheight);        } mtasks.remove (this);        /** * Add picture to LinearLayout * * @param bitmap * @param scaleheight */ public void AddImage (Bitmap Bitmap, float width, float sCaleheight) {//Generate scaled IV ImageView IV = new ImageView (mcontext);            Android.view.ViewGroup.LayoutParams params = new Layoutparams ((int) width, (int) scaleheight);            Iv.setlayoutparams (params);                if (bitmap! = null) {//resolves the default picture with a small problem iv.setscaletype (SCALETYPE.FIT_XY);                Iv.setpadding (5, 5, 5, 5);                Iv.setimagebitmap (bitmap);                Iv.settag (R.string.iamgurl, Mimageurl);                Findcolumntoadd (iv, (int) scaleheight). AddView (iv);            Mimageviewlist.add (iv);        }}} private Bitmap DownLoad (String imageUrl) throws IOException {Bufferedinputstream bis = null;        FileOutputStream fos = null;        Bufferedoutputstream BOS = NULL;        HttpURLConnection conn = null;        File imagefile = null;            try {URL url = new URL (imageUrl); conn = (httpurlconnection) url.openconnection ();           Conn.setreadtimeout (10000);            Conn.setconnecttimeout (5000);            Conn.setdoinput (TRUE);            Conn.setdooutput (TRUE);            InputStream is = Conn.getinputstream ();            ImageFile = new File (Getimagepath (IMAGEURL));            bis = new Bufferedinputstream (IS);            FOS = new FileOutputStream (imagefile);            BOS = new Bufferedoutputstream (FOS);            int len = 0;            byte[] buffer = new byte[1024];                while (len = bis.read (buffer))! =-1) {bos.write (buffer, 0, Len);            Bos.flush ();        }} catch (Exception e) {e.printstacktrace ();            } finally {if (bis! = null) {bis.close ();            } if (bos! = null) {bos.close ();            } if (conn! = null) {conn.disconnect (); }}//If ImageFile is not NULL, add the picture to memory if (imagefile! = null) {BItmap bitmap = Bitmapfactory.decodefile (Imagefile.getpath ());            Mimagesthoumb.addbitmaptomemorycache (ImageUrl, bitmap);        return bitmap;    } return null; }/** * Determine if there is a picture sdcard picture, if there is a use, no download * * @param mimageurl * @return * */Public Bitmap LoadImage (S        Tring Mimageurl) throws Exception {File File = new file (Getimagepath (Mimageurl));        if (!file.exists ()) {downLoad (Mimageurl); if (Mimageurl! = null) {//process local picture, set size to prevent oom Bitmap Bitmap = mimagesthoumb.decodesimplebitm            Apfromresource (File.getpath (), mclolumnwidth);            Bitmap Bitmap = Bitmapfactory.decodefile (File.getpath ());                if (bitmap! = null) {Mimagesthoumb.addbitmaptomemorycache (Mimageurl, bitmap);            return bitmap;    }} return null; /** * Find the column to add * * @param IV */Private LinearLayout FindcolumnToadd (ImageView IV, int imageheight) {if (mfirstcolumnheight <= msecondcolumnheight) {if (Mfirstcol                Umnheight <= mthirdcolumnheight) {Iv.settag (r.string.border_top, mfirstcolumnheight);                Mfirstcolumnheight + = ImageHeight;                Iv.settag (R.string.border_bottom, mfirstcolumnheight);            return mfirstcolumn;            } iv.settag (R.string.border_top, mthirdcolumnheight);            Mthirdcolumnheight + = ImageHeight;            Iv.settag (R.string.border_bottom, mthirdcolumnheight);        return mthirdcolumn; } else {if (msecondcolumnheight <= mthirdcolumnheight) {Iv.settag (R.string.border_top, MSec                Ondcolumnheight);                Msecondcolumnheight + = ImageHeight;                Iv.settag (R.string.border_bottom, msecondcolumnheight);            return msecondcolumn;            } iv.settag (R.string.border_top, mthirdcolumnheight); MthiRdcolumnheight + = ImageHeight;            Iv.settag (R.string.border_bottom, mthirdcolumnheight);        return mthirdcolumn; }}/** * Get the file address * * @param IMAGEURL * @return * * * private string Getimagepath (string image        URL) {int lastIndexOf = Imageurl.lastindexof ("/");        String imageName = imageurl.substring (lastIndexOf + 1);        String Imagedir = Environment.getexternalstoragedirectory (). GetPath () + "/pangzaifei/";        File File = new file (Imagedir);        if (!file.exists ()) {File.mkdir ();        } String ImagePath = Imagedir + imageName;    return imagePath; /** * Get the name of the picture * * @param IMAGEURL */Private Boolean Hashsdcard () {if (environment.getext        Ernalstoragestate (). Equals (environment.media_mounted)) {return true;    } return false; } @Override/** * When the gesture is lifted, start each 5 millisecond compute position */public Boolean OnTouch (View V, motionevent event) {if (event.getaction () = = motionevent.action_up) {//Send handler M            Essage msg = Mhandler.obtainmessage ();            Msg.obj = this;        Mhandler.sendmessagedelayed (msg, mdelay);    } return false;            } private Handler Mhandler = new Handler () {@Override public void Handlemessage (Message msg) {            Super.handlemessage (msg); Determine if you have slipped to the lowest point, if you have slipped to the lowest point, load more pages, or continue to send handler scan photofallscrollview ScrollView = (photofallscrollview) msg.obj            ;            int scrolly = scrollview.getscrolly ();                        if (scrolly = = lastscrolly) {if (mscrollviewheight + scrolly >= mscrolllayout.getheight ()                && Mtasks.isempty ()) {scrollview.loadmoreimages ();            } scrollview.checkvisibile ();                } else {lastscrolly = scrolly;    Message message = new Message ();            Message.obj = ScrollView;            mhandler.sendmessagedelayed (message, mdelay);    }        }    };    private int mscrollviewheight;    Private View mscrolllayout; /** * want invisible to empty picture */protected void Checkvisibile () {if (mimageviewlist! = null && mimageviewlis T.size () > 0) {for (int i = 0; i < mimageviewlist.size (); i++) {ImageView IV = Mimagevie                Wlist.get (i);                int bordertop = (int) iv.gettag (r.string.border_top);                int borderbottom = (int) iv.gettag (r.string.border_bottom);                    if (BorderBottom > getscrolly () && bordertop < getscrolly () + mscrollviewheight) {                    String imageUrl = (string) iv.gettag (R.string.iamgurl); if (IMAGEURL! = NULL &&! "".                        Equals (IMAGEURL)) {Bitmap Bitmap = Mimagesthoumb.getmemorycache (IMAGEURL); if (Bitmap! = Null) {Iv.setimagebitmap (bitmap);                        } else {downloaddata (IMAGEURL);                }}}} else {Iv.setimageresource (R.drawable.empty_photo); }            }        }    }}
Above is the main thing, ideas and comments have been added. One of the tags in ImageView I want to explain, the main save the top and bottom margin of each column and the URL of the picture, this method is to display only the picture of the current page.

Layout file:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "> <com. Pangzaifei.falls.PhotoFallScrollView android:layout_width= "fill_parent" android:layout_height= "Fill_parent"             > <linearlayout android:layout_width= "fill_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:lay out_weight= "1" android:orientation= "vertical" > </LinearLayout> <linearla Yout android:id= "@+id/second_column" android:layout_width= "0DP" android:layou T_height= "Wrap_content" Android:layout_weight= "1" android:orientation= "vertical" > </LinearLayout> <linea Rlayout android:id= "@+id/third_column" android:layout_width= "0DP" Android:lay            out_height= "Wrap_content" android:layout_weight= "1" android:orientation= "vertical" > </LinearLayout> </LinearLayout> </com.pangzaifei.falls.photofallscrollview></linearl Ayout>

:



Source Address:

http://download.csdn.net/detail/pangzaifei/7639423





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.