Android Landscape ScrollView Photo Browser implementation (tribute to Guo Shen)

Source: Internet
Author: User

Because the project needs to be implemented in a landscape photo browser, using a horizontal Srollview implementation.

The implementation results are as follows:


Implementation ideas:

Before beginning to do, in the spirit of wheels with wheels, but also to Baidu for a long time, such as "Android landscape photo Wall", "Android landscape Photo Stream", "Android Landscape photo Selector" ... It's completely not good. Check to find out are those several vertical photo waterfall flow, horizontal anyway I did not find.

Then, after reading the article "Ndroid Waterfall flow photo wall realization, experience irregular arrangement of beauty" after reading (http://blog.csdn.net/guolin_blog/article/details/10470797), Ling chicken Guo Shen, Think that since the vertical can be achieved, then the horizontal is not to turn a direction is good?

Although it took a little time to realize it, the basic principle seemed to be in a direction ... But the revised code and Guo Shen source, although the picture loading section we did not change, but in many places is still very big difference. Here's a special note.

The points to note are the following three areas:

1, no longer inherit from ordinary ScrollView but inherit from Horizontalscrollview.

2, in the initialization of OnLayout no longer initialize three columns of photos (Guo Shen write waterfall flow ~), but instead of a horizontal column, and make each picture of the width of the equal, so that it remains square.

3, in the visibility of judgment is no longer based on the height of the judge according to the width:

    /**     * Iterates through each picture in the imageviewlist, checks the visibility of the picture, and replaces the picture with an empty image if it has already left the visible range of the screen.     */public    void Checkvisibility () {for        (int i = 0; i < imageviewlist.size (); i++) {            ImageView Imagevie W = imageviewlist.get (i);            int borderleft = (Integer) imageview.gettag (r.string.border_top);            int borderright = (Integer) ImageView                    . Gettag (r.string.border_bottom);            if (Borderleft > Getscrollx ()                    && borderright < Getscrollx () + columnwith) {                String imageUrl = (Str ing) Imageview.gettag (r.string.image_url);                Get picture from memory                Bitmap Bitmap = Ngimageloader.getbitmapfrommemorycache (IMAGEURL);                if (bitmap!=null) {                    imageview.setimagebitmap (bitmap);                } else {                    //todo display null                }            } else {            }        }    }

The source code is implemented as follows:

Package Com.whale.nangua.toquan.view;import Android.content.context;import Android.content.res.resources;import Android.graphics.bitmap;import Android.os.asynctask;import Android.os.environment;import Android.os.Handler; Import Android.os.message;import android.util.attributeset;import android.util.log;import android.util.TypedValue; Import Android.view.gesturedetector;import Android.view.motionevent;import Android.view.view;import Android.view.viewgroup;import Android.widget.framelayout;import Android.widget.horizontalscrollview;import Android.widget.imagebutton;import Android.widget.imageview;import Android.widget.linearlayout;import Android.widget.toast;import Com.whale.nangua.toquan.r;import Com.whale.nangua.toquan.userinfoactivity;import Java.io.bufferedinputstream;import Java.io.bufferedoutputstream;import Java.io.file;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.net.httpurlconnection;import Java.net.URL;import Java.util.arraylist;import Java.util.HashSet;Import Java.util.list;import java.util.set;/** * Created by Nangua on 2016/8/3.     */public class Ngothersinfoatyhorizotalscrollview extends Horizontalscrollview implements view.ontouchlistener{/**    * has the layout been loaded once, where initialization in onlayout only needs to be loaded once */private Boolean loadonce;    /** * Column Layout */private linearlayout linearlayout_userinfo_personal_column;    /** * Total Width * */private static int columnwith;    /** * Width of each picture */private int perphotowidth;     /** * Record the scrolling distance in the vertical direction.    */private static int lastscrollx =-1;     /** * Direct sub-layout under Myscrollview.    */private static View scrolllayout; /** * Perform some critical initialization operations, Ngothersinfoatyhorizotalscrollview, and get the height value.     and start loading the picture on the first page here. */@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 (); Linearlayout_userinfo_personal_column = nEW LinearLayout (GetContext ()); Linearlayout_userinfo_personal_column.setlayoutparams (New Linearlayout.layoutparams (ViewGroup.LayoutPa Rams.            Wrap_content, ViewGroup.LayoutParams.MATCH_PARENT));            Linearlayout_userinfo_personal_column.setorientation (linearlayout.horizontal);            This.addview (Linearlayout_userinfo_personal_column);  Perphotowidth = Scrollviewheight;            The width of each picture is equal to the column height loadonce = true;            Load next page picture loadmoreimages ();        Scrolllayout = Getchildat (0);    }}/** * record is currently loaded to page * @param context */private int page = 0;    /** * Number of images to load per page * default is 5 * @param context */public static final int page_size = 5;     /** * Logs All tasks that are downloading or waiting to be downloaded.    */private static set<loadimagetask> taskcollection;    /** * Image Management Tool class */private Com.whale.nangua.toquan.utils.NGImageLoader ngimageloader;  /**   * Myscrollview the height of the layout.    */private static int scrollviewheight;     /** * Myscrollview constructor function. * @param context * @param attrs */Public Ngothersinfoatyhorizotalscrollview (context context, AttributeSet attr        s) {Super (context, attrs);        Ngimageloader = Ngimageloader.getinstance ();        Taskcollection = new hashset<loadimagetask> ();    Setontouchlistener (this);     /** * The image visibility Check in the handler, as well as loading more pictures of the operation.            */private static Handler Handler = new Handler () {public void Handlemessage (Android.os.Message msg) {            Ngothersinfoatyhorizotalscrollview Myscrollview = (ngothersinfoatyhorizotalscrollview) msg.obj;            int scrollx = MYSCROLLVIEW.GETSCROLLX ();                If the current scroll position is the same as the last time, indicates that the scrolling if (scrollx = = LASTSCROLLX) {///when scrolling to the right, and there is currently no task being downloaded, starts loading the next page of the picture if (Columnwith + scrollx >= (Scrolllayout.getwidth ()) && taskcollection.is Empty ()) {myscrollview.loadmoreimages ();            } myscrollview.checkvisibility ();                } else {lastscrollx = SCROLLX;                Message message = new Message ();                Message.obj = Myscrollview;            The scrolling position is judged again after 5 milliseconds handler.sendmessagedelayed (message, 5);    }        }    };     /** * Monitor the user's touchscreen event and start rolling detection if the user's finger leaves the screen. */@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;     }/** * Iterates through each picture in the imageviewlist, checks the visibility of the picture, and replaces the picture with an empty image if the picture has left the visible extent of the screen. */public void checkvisibility () {for (int i = 0; i < imageviewlist.size (); i++) {ImageView imag            Eview = Imageviewlist.get (i); int borderleft = (Integer) imageView. Gettag (R.string.border_top);            int borderright = (Integer) imageView. Gettag (R.string.border_bottom);                if (Borderleft > Getscrollx () && borderright < Getscrollx () + Columnwith) {                String imageUrl = (string) imageview.gettag (R.string.image_url);                Get picture from memory Bitmap Bitmap = Ngimageloader.getbitmapfrommemorycache (IMAGEURL);                if (bitmap!=null) {imageview.setimagebitmap (bitmap); }else {//todo display null}} else {}}} static Boolean H    Asover = false;    Private string[] Imageurls;    public void Setimageurls (string[] imageurls) {this.imageurls = Imageurls;     }/** * starts loading the next page of images, each of which opens an asynchronous thread to download. */public void loadmoreimages () {if (Hassdcard () && imageurls!=null) {//Determine if there is an SD card int starti  Ndex = page * page_size; Starting bitPlace int endIndex = page * page_size + page_size; End Position if (StartIndex < imageurls.length) {//toast.maketext (GetContext (), "Loading ...", TOAST.L                Ength_short). Show ();                if (EndIndex > Imageurls.length) {endIndex = Imageurls.length; } for (int i = StartIndex; i < EndIndex; i++) {//Load picture Loadimageta                    SK task = new Loadimagetask ();                    Taskcollection.add (Task);                Task.execute (Imageurls[i]);            } page++; } else {if (Hasover = = False) {Toast.maketext (GetContext (), "No More pictures", toast.length_sh                    ORT). Show ();                Hasover = true;        }}} else {//toast.maketext (GetContext (), "No SD card found", Toast.length_short). Show ();     }}/** * Determine if the phone has an SD card.     * @return have SD card return True, no return false. */priVate Boolean Hassdcard () {return Environment.MEDIA_MOUNTED.equals (environment. Getexternalstoragest    Ate ());  } public int Dptopx (Resources res, int dp) {return (int) typedvalue.applydimension (Typedvalue.complex_unit_dip,    DP, Res.getdisplaymetrics ());     /** * Record all the images on the screen to control the release of the image at any time.    */private list<imageview> imageviewlist = new arraylist<imageview> ();     /** * task of downloading pictures asynchronously.        * * @author Guolin */class Loadimagetask extends Asynctask<string, Void, bitmap> {@Override        public boolean equals (Object o) {return super.equals (o);        } @Override public int hashcode () {return super.hashcode ();        }/** * Image URL address */private String Mimageurl;        /** * Reusable ImageView */private ImageView Mimageview;      Public Loadimagetask () {}/** * Incoming REUSABLE ImageView *   * @param imageView */Public Loadimagetask (ImageView imageView) {mimageview = ImageView;            } @Override protected Bitmap doinbackground (String ... params) {mimageurl = params[0];            Bitmap Imagebitmap = Ngimageloader. Getbitmapfrommemorycache (Mimageurl);            if (Imagebitmap = = null) {Imagebitmap = LoadImage (Mimageurl);        } return Imagebitmap; } @Override protected void OnPostExecute (Bitmap Bitmap) {if (Bitmap! = null) {AD            DIMAGE (Bitmap, Perphotowidth, perphotowidth);        } taskcollection.remove (this); /** * Loads the picture based on the URL that was passed in.         If the image already exists in the SD card, it is read directly from the SD card, otherwise it will be downloaded from the network.         * * @param imageUrl * Picture URL address * @return the picture loaded into memory. */Private Bitmap LoadImage (String imageUrl) {File ImageFile = new File (Getimagepath (imageurL));            if (!imagefile.exists ()) {downloadimage (IMAGEURL);                        } if (IMAGEURL! = null) {Bitmap Bitmap = Ngimageloader.decodesampledbitmapfromresource (                Imagefile.getpath (), perphotowidth);                    if (bitmap! = null) {Ngimageloader.addbitmaptomemorycache (imageUrl, bitmap);                return bitmap;        }} return null; }/** * Add a picture to ImageView * * @param bitmap * Images to add * @param im  Agewidth * Picture Width * @param imageheight * Image Height */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 (ImageView.ScaleType.FIT_XY);                Imageview.setpadding (5, 5, 5, 5);                Imageview.settag (R.string.image_url, Mimageurl);                Here the current position of the picture should be computed//Imageview.settag (R.string.border_top, firstcolumnheight);                Imageview.settag (R.string.border_top, Columnwith);                Columnwith + = perphotowidth;//Increase total width imageview.settag (r.string.border_bottom, Columnwith);                Linearlayout_userinfo_personal_column.addview (ImageView);            Imageviewlist.add (ImageView);         }}/** * Download images to SD card cache.         * * @param imageUrl * The URL address of the picture.     */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 = Ngimageloader.decodesampledbitmapfromres                Ource (Imagefile.getpath (), perphotowidth);                if (bitmap! = null) {Ngimageloader.addbitmaptomemorycache (imageUrl, bitmap);         }}}/** * Gets the local storage path for the picture.         * * @param imageUrl * The URL address of the picture.         * @return The local storage path of the picture.     */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; }    }}

Qaq Monday is really a day sleepy ah ~ tomorrow still have to climb up to work ~ refueling for themselves ~


Android Landscape ScrollView Photo Browser implementation (tribute to Guo Shen)

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.