Listview Optimization for Android (lrucache is used, default image is used when the image slides, and loading is stopped)

Source: Internet
Author: User

Note: lrucache has version restrictions, and earlier sdks need to add corresponding support-4v files in the libs folder.
Most of the changes in this article are described at http://www.iteye.com/topic/1118828. thank you.
If there is a key comment in the project code without talking nonsense, the project will not be uploaded, And you can modify it against the above URL.

The application file is used to create an image storage Folder:

public class MyApp extends Application{    @Override    public void onCreate() {        super.onCreate();        File f = new File(Environment.getExternalStorageDirectory()+"/TestSyncListView/pic/");        if (!f.exists()) {            f.mkdirs();        }    }}

Image reading tool:

Public class syncimageloaderutil {private object lock = new object (); Private Boolean mallowload = true; private Boolean firstload = true; private int mstartloadlimit = 0; private int mstoploadlimit = 0; final handler = new handler (); // Private hashmap <string, softreference <drawable> imagecache = new hashmap <string, softreference <drawable> (); private lrucache <string, bitmap> mmemorycache; Runinotherthread runinoutherthread; Public syncimageloaderutil (context) {super (); int memclass = (activitymanager) context. getsystemservice (context. activity_service )). getmemoryclass (); int cachesize = 1024*1024 * memclass/8; mmemorycache = new lrucache <string, bitmap> (cachesize) {@ override protected int sizeof (string key, bitmap value) {// todo auto-generated method stub Return Value. Getrowbytes () ;}}; runinoutherthread = new runinotherthread (); runinoutherthread. start ();} public interface onimageloadlistener {public void onimageload (integer T, drawable); Public void onerror (integer T);} public void setloadlimit (INT startloadlimit, int stoploadlimit) {If (startloadlimit> stoploadlimit) {// logutil. I ("test", startloadlimit + "-- error ---" + stoploadlimit); return;} MS Tartloadlimit = startloadlimit; mstoploadlimit = stoploadlimit;} public void restore () {mallowload = true; firstload = true;} public void lock () {mallowload = false; firstload = false ;} public void unlock () {mallowload = true; synchronized (LOCK) {lock. policyall () ;}} public void LoadImage (integer T, string imageurl, onimageloadlistener listener) {final onimageloadlistener mlistener = lis Tener; final string mimageurl = imageurl; Final integer Mt = T; runinoutherthread. gethandler (). Post (New runnable () {@ override public void run () {If (! Mallowload) {synchronized (LOCK) {try {lock. wait ();} catch (interruptedexception e) {// todo auto-generated Catch Block E. printstacktrace () ;}} if (mallowload & firstload) {LoadImage (mimageurl, MT, mlistener);} // logutil. E ("test", "original start:" + mstartloadlimit + "original current location:" + MT + "Original End:" + mstoploadlimit ); if (mallowload & mt <= mstoploadlimit & mt> = mstartloadlimit) {// logutil. E ("test", "Start:" + MS Tartloadlimit + "current location:" + MT + "end:" + mstoploadlimit); LoadImage (mimageurl, MT, mlistener );}}});} private void LoadImage (final string mimageurl, final integer Mt, final onimageloadlistener mlistener) {If (mimageurl! = NULL & mmemorycache. Get (mimageurl )! = NULL) {// softreference <drawable> softreference = imagecache. get (mimageurl); Final drawable d = new bitmapdrawable (mmemorycache. get (mimageurl); // logutil. D ("PPP", "drawable:" + d); If (D! = NULL) {handler. post (New runnable () {@ override public void run () {If (mallowload) {mlistener. onimageload (MT, d) ;}}); return ;}try {final drawable d = loadimagefromurl (mimageurl); If (D! = NULL) {mmemorycache. put (mimageurl, (bitmapdrawable) d ). getbitmap ();} handler. post (New runnable () {@ override public void run () {If (mallowload) {mlistener. onimageload (MT, d) ;}}) ;}catch (ioexception e) {handler. post (New runnable () {@ override public void run () {mlistener. onerror (MT) ;}}); E. printstacktrace () ;}} public static drawable loadimagefromurl (string URL) throws ioexception {// Debugutil. debug (URL); If (environment. getexternalstoragestate (). equals (environment. media_mounted) {file F = new file (environment. getexternalstoragedirectory () + "/weiyu/PIC/" + md5util. getmd5 (URL. getbytes (); If (F. exists () {fileinputstream FD = new fileinputstream (f); drawable d = drawable. createfromstream (FCM, "src"); Return D;} url m = new URL (URL); inputstream I = (inputstream) M. g Etcontent (); datainputstream in = new datainputstream (I); fileoutputstream out = new fileoutputstream (f); byte [] buffer = new byte [1024]; int byteread = 0; while (byteread = in. read (buffer ))! =-1) {out. write (buffer, 0, byteread);} In. close (); out. close (); Return loadimagefromurl (URL);} else {url m = new URL (URL); inputstream I = (inputstream) M. getcontent (); drawable d = drawable. createfromstream (I, "src"); Return D ;}}}

  
Thread helper class:

public class RunInOtherThread {private static final String LOG_TAG = "RunInOtherThread";          private LooperThread localThread = new LooperThread();            private boolean isRunning = true;        public Handler getHandler(){          return localThread.getHandler();      }            private class LooperThread extends Thread {          private Handler mHandler;            public void run() {              Looper.prepare();              mHandler = new Handler() {                  public void handleMessage(Message msg) {                      onReceiveMessage(msg.what);                  }              };              Looper.loop();          }                    Handler getHandler(){              return mHandler;          }           }            public void start(){          localThread.start();      }            public void quit(){          localThread.getHandler().getLooper().quit();      }            public void sendMessage(int what){          getHandler().sendEmptyMessage(what);      }            public Thread getThread(){          return localThread;      }            public void onReceiveMessage(int what){};}

  
Usage class:

// Instantiate the tool class syncimageloaderutil syncimageloader = new syncimageloaderutil (mcontext); syncimageloader. loadImage (Position, model. mpic, imageloadlistener); // application interface: parameter 1: Position of the image to be loaded; parameter 2: imageview to be loaded; parameter 3: callback interface // map key to be saved, the value is the hashmap map = new hashmap (); map of the corresponding position of the listview. put (Position, convertview); syncimageloaderutil. onimageloadlistener imageloadlistener = new syncimageloaderutil. onimageloadlistener () {@ overridepub LIC void onimageload (integer T, drawable) {view = (View) map. Get (t); If (view! = NULL) {imageview IV = (imageview) view. findviewbyid (R. id. image); IV. setbackgrounddrawable (drawable) ;}@ overridepublic void onerror (integer t) {// image loading failed // get the content layout of the row at the corresponding position of the listview musicmodel = (musicmodel) getitem (t); view = mlistview. findviewwithtag (model); If (view! = NULL) {imageview IV = (imageview) view. findviewbyid (R. id. image); IV. setbackgroundresource (R. drawable. img_pic) ;}}; // implementation class and the onscrolllistener interface public void LoadImage () {// do not use the getfirstvisibleposition method of listview here, if (end> = getcount () {end = getcount ()-1;} syncimageloader. setloadlimit (START, end); syncimageloader. unlock () ;}@ overridepublic void onscrollstatechanged (abslistview view, int scro Llstate) {// todo auto-generated method stubif (lodingview) {Switch (scrollstate) {Case abslistview. onscrolllistener. scroll_state_fling: syncimageloader. lock (); break; Case abslistview. onscrolllistener. scroll_state_idle: LoadImage (); break; Case abslistview. onscrolllistener. scroll_state_touch_scroll: syncimageloader. lock (); break; default: break; }}@ overridepublic void onscroll (abslistview view, int firstvi Sibleitem, int visibleitemcount, int totalitemcount) {// The position obtained here is more accurate, however, there will also be a special odd model that cannot be used. // start and end are the Defined variables: Start = firstvisibleitem; end = firstvisibleitem + visibleitemcount; If (firstvisibleitem! = 0) {// lodingview is the control variable used to control the first incoming view loading and reading image lodingview = true;} else {lodingview = false; LoadImage ();}}
Related Article

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.