Optimize the GridView View cache on the android tablet

Source: Internet
Author: User

Recently, I am working on the android tablet, which involves the performance problem of using the GridView with high resolution. In Android mobile phone software development, if a large number of items are used on ListView or GridView, many people will think of ViewHolder ...... yes, ViewHolder is very suitable for ListView or a GridView with less than four items in each row. However, for a high-resolution device (android tablet or even android TV), if each line contains more than four items, ViewHolder is still used.

For example, if there are nine items in each row and the images of each Item are dynamically downloaded from the network, the optimization of the GridView view is a test.

The optimization method proposed in this article is: Create a View List (List <View>) in getView (), save the recently constructed View, and read it directly from the View List during rollback, instead of dynamic building. Using this method has two advantages:

1. Quickly read past items;

2. Directly Save the View instead of Bitmap, avoiding the delay caused by ImageView. setImageBitmaps.

Of course, the disadvantage is a waste of memory. Therefore, you must set an upper limit to delete the oldest Item if the limit is exceeded.
Let's take a look at the performance comparison between this method and ViewHolder:


Compare the three groups of data that the 100 items are rolled down, for example:
The speed of "CacheAdapter caching 50 items" is very close to that of ViewHolderAdapter. Because CacheAdapter has a cache, there will be 1 ~ Two quick reads of Item (10 ~ 20), while ViewHolder's reading speed per Item is average.
"CacheAdapter caches 75 items" only takes a long time to scroll down for the first time. The cached items are used for the second time, so the speed is much faster.

 

 

 

Compare the three groups of data to which 100 items are rolled up, for example:

"CacheAdapter caches 50 items" slightly faster than ViewHolderAdapter, and "CacheAdapter caches 75 items" is still the fastest.
Summary: The speed of "CacheAdapter caching 50 items" is slightly faster than that of HolderView. The fastest speed of reading the most recent items is, and the faster the cached items are. The "CacheAdapter caches 75 items" occupies the least memory. This is because some images fail to be downloaded and the image of the saved Item is empty. In fact, the larger the cache, the more memory the Item occupies.

PS: asynchronous reading of network images is used here. The successful download takes up a large amount of memory, and the download failed takes up a small amount of memory. Therefore, the memory usage is not the absolute value of a moment, memory usage is for reference only .....

CacheAdapter. java is the custom Adapter for implementing cached items. The source code is as follows:

/**
* Use the list to cache previous items
* @ Author hellogv
*
*/
Public class CacheAdapter extends BaseAdapter {

Public class Item {
Public String itemImageURL;
Public String itemTitle;
Public Item (String itemImageURL, String itemTitle ){
This. itemImageURL = itemImageURL;
This. itemTitle = itemTitle;
}
}

Private Context mContext;
Private ArrayList <Item> mItems = new ArrayList <Item> ();
LayoutInflater inflater;
Public CacheAdapter (Context c ){
MContext = c;
Inflater = (LayoutInflater) mContext. getSystemService (Context. LAYOUT_INFLATER_SERVICE );
}

Public void addItem (String itemImageURL, String itemTitle ){
MItems. add (new Item (itemImageURL, itemTitle ));
}

Public int getCount (){
Return mItems. size ();
}

Public Item getItem (int position ){
Return mItems. get (position );
}

Public long getItemId (int position ){
Return position;
}
 
List <Integer> lstPosition = new ArrayList <Integer> ();
List <View> lstView = new ArrayList <View> ();
 
List <Integer> lstTimes = new ArrayList <Integer> ();
Long startTime = 0;
Public View getView (int position, View convertView, ViewGroup parent ){
StartTime = System. nanoTime ();

If (lstPosition. contains (position) = false ){
If (lstPosition. size ()> 75) // set the number of cached items.
{
LstPosition. remove (0); // Delete the first entry
LstView. remove (0); // Delete the first entry
}
ConvertView = inflater. inflate (R. layout. item, null );
TextView text = (TextView) convertView. findViewById (R. id. itemText );
ImageView icon = (ImageView) convertView. findViewById (R. id. itemImage );
Text. setText (mItems. get (position). itemTitle );
New asyncloadimage(cmd.exe cute (new Object [] {icon, mItems. get (position). itemImageURL });

LstPosition. add (position); // add the latest entry
LstView. add (convertView); // add the latest entry
} Else
{
ConvertView = lstView. get (lstPosition. indexOf (position ));
}

Int endTime = (int) (System. nanoTime ()-startTime );
LstTimes. add (endTime );
If (lstTimes. size () = 10)
{
Int total = 0;
For (int I = 0; I <lstTimes. size (); I ++)
Total = total + lstTimes. get (I );
 
Log. e ("10 elapsed time:" + total/1000 + "μs ",
"Memory used:" + Runtime. getRuntime (). totalMemory ()/1024 + "KB ");
LstTimes. clear ();
}

Return convertView;
}

/**
* Asynchronously reading network images
* @ Author hellogv
*/
Class AsyncLoadImage extends AsyncTask <Object, Object, Void> {
@ Override
Protected Void doInBackground (Object... params ){

Try {
ImageView imageView = (ImageView) params [0];
String url = (String) params [1];
Bitmap bitmap = getBitmapByUrl (url );
PublishProgress (new Object [] {imageView, bitmap });
} Catch (MalformedURLException e ){
Log. e ("error", e. getMessage ());
E. printStackTrace ();
} Catch (IOException e ){
Log. e ("error", e. getMessage ());
E. printStackTrace ();
}
Return null;
}

Protected void onProgressUpdate (Object... progress ){
ImageView imageView = (ImageView) progress [0];
ImageView. setImageBitmap (Bitmap) progress [1]);
}
}

Static public Bitmap getBitmapByUrl (String urlString)
Throws MalformedURLException, IOException {
URL url = new URL (urlString );
URLConnection connection = url. openConnection ();
Connection. setConnectTimeout (25000 );
Connection. setReadTimeout (90000 );
Bitmap bitmap = BitmapFactory. decodeStream (connection. getInputStream ());
Return bitmap;
}
}
 

Among them, if (lstPosition. size ()> 75) is the key to setting the number of cached items. Here 75 items are cached.

ViewHolderAdapter. java is a custom Adapter that enables ViewHolder to load items. The source code is as follows:

/**
* Use ViewHolder to load Item
* @ Author hellogv
*
*/
Public class ViewHolderAdapter extends BaseAdapter {

Public class Item {
Public String itemImageURL;
Public String itemTitle;

Public Item (String itemImageURL, String itemTitle ){
& N

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.