微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

android – 在网格视图中显示图像的最佳方式是滚动平滑

首先,我已经做了很少的事情来在gridview中显示图像,使滚动时变得平滑

1.从背景线程上的互联网加载图像

AsyncTask acyncTask ;
HandlerThread handlerThread ;

 URL imageUrl = new URL(link);

2.将位图设置为样本大小以节省内存

final BitmapFactory.Options option = new BitmapFactory.Options();
    option.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(mFile.getPath(),option);
    option.inSampleSize = calculateInSampleSize(option,mSize,mSize);
    option.inJustDecodeBounds = false;
    option.inPurgeable = true ;
    option.inDither = false ;
    option.inScaled = false ;
    option.inPreferredConfig = Bitmap.Config.ARGB_8888;

3.制作缓存以保存解码的位图

LruCache lruCache = new LruCache

在baseadapter getView();
我将lruCache.get(key)取得解码后的位图

4.通过处理程序解码位图时的延迟加载

 Handler handler = new Handler();
        handler.post(new Runnable(){
           public void run(){
              imageView.setimageBitmap(bitmap);
          }
      });

现在我面临一个大问题,当我滚动时它仍然有点滞后
我有谷歌的东西可以使滚动更好,不知道真的有什么可以改善或问题出来的地方我检查每个getView()只花我约2~6毫秒它会调用我的代码异步加载图像表单工作线程,所以我真的不知道为什么有些应用程序可以加载非常流畅?我的情况是当滚动屏幕看起来不是很顺利是否有一些建议可以适用?

编辑:当我滚动时,在缓存中找到位图并在屏幕上显示,如果我快速滚动,它看起来就像没有滚动到足以显示图像,它会使我的滚动不那么顺利,即使我有缓存下来缓存中的位图

这是适配器代码

if (convertView == null) {
        convertView = layoutInflater.inflate(
                R.layout.row_display_image_grid,null);
        viewHolder = new displayImageGridViewHolder();
        viewHolder.background = (RelativeLayout) convertView
                .findViewById(R.id.background);
        viewHolder.image = (ImageView) convertView.findViewById(R.id.image);
        viewHolder.text = (TextView) convertView.findViewById(R.id.text);
        viewHolder.position = position;
        viewHolder.text.setEllipsize(TruncateAt.END);
        viewHolder.text.setTypeface(typeFace);
        viewHolder.image.setonClickListener(this);
        viewHolder.image.setonLongClickListener(this);
        convertView.setTag(viewHolder);
    } else {
        viewHolder = (displayImageGridViewHolder) convertView.getTag();
    }

viewHolder.position = position;
imageLoader.loadImage(imageLinkList.get(position),viewHolder.image);
return convertView;
最佳答案
下面是我使用的LazyLoader的示例.注意我使用SoftReferences作为位图,现在使用LruCache可以更好地服务.

这将从web / sdcard / memory异步加载图像,并从占位符图像创建淡入效果.

public class ImageLoader {

private static MemoryCacheNew memoryCache=new MemoryCacheNew();
private static FileCache fileCache;

private static BitmapFactory.Options bitmapOptions;

private static int mInSampleSize;



public ImageLoader(Context context,int inSampleSize){


    fileCache=new FileCache(context);        

    context = null;

    bitmapOptions = new BitmapFactory.Options();
    bitmapOptions.inSampleSize = mInSampleSize = inSampleSize;
    bitmapOptions.inPreferredConfig = Config.RGB_565;
    bitmapOptions.inInputShareable = true;
    bitmapOptions.inDither = false;

}

final static int PLACEHOLDER_IMAGE = R.drawable.store_placeholder;

public void displayImage(String url,ImageView imageView,boolean checkTags){

    try{

    new AsyncPhotoTask(imageView,url,checkTags).execute();

    }catch(Exception e){
        e.printstacktrace();
    }

}

public void displayImage(String url,ImageView imageView)
{
      displayImage(url,imageView,true); 

}


private static Bitmap getBitmap(String url) 
{
    File f=fileCache.getFile(url);


    if(f!= null){
    //from SD cache
    Bitmap b = decodeFile(f);
    if(b!=null)
        return b;
    }

    //from web
    try {
        Bitmap bitmap=null;

        URL imageUrl;

            imageUrl = new URL(url);


        HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.copyStream(is,os);
        is.close();
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Exception ex){
       ex.printstacktrace();
       return null;
    }
}

//decodes image and scales it to reduce memory consumption
private static Bitmap decodeFile(File f){
    try {
        return BitmapFactory.decodeStream(new FileInputStream(f),null,bitmapOptions);

    } catch (FileNotFoundException e) {

    } catch (OutOfMemoryError err){
        System.gc();
    } 

    return null;
}


private static class AsyncPhotoLoad extends AsyncTaskprintstacktrace();
        }

        return transition;
    }

    @Override
    protected void onPostExecute(TransitionDrawable result) {
        if(result != null){
            try{            
                if(checkTags){                      
                        String tag = (String)imageView.getTag();    
                        if(!tag.equals(url)){
                            return;
                        }
                }

                   imageView.setimageDrawable(result);
                   result.startTransition(300);



            } catch(Exception e){
                e.printstacktrace();
            }
        } else {
            if(checkTags){
            try{
                String tag = (String)imageView.getTag();    
                if(!tag.equals(url))
                    return;

            }catch(Exception e){
                e.printstacktrace();
            }
            }


        }
    }

}



private static class AsyncPhotoTask extends AsyncTaskarams) {
        try{
        if(checkTags)
            imageView.setTag(url);  

        }catch(Exception e){
            e.printstacktrace();
        }

        return memoryCache.get(url,mInSampleSize);
    }


    @Override
    protected void onPostExecute(Bitmap result) {
        try{
        if(result!=null && !result.isRecycled()){


            imageView.setimageBitmap(result);   
        }
        else
        {   

            imageView.setimageResource(PLACEHOLDER_IMAGE);            
            new AsyncPhotoLoad(imageView,checkTags).execute();      

        }    

        }catch(Exception e){
            e.printstacktrace();
        }
    }



}





public static void clearCache() {
    memoryCache.clear();
    fileCache.clear();
}

public static void clearMemory(){
    memoryCache.clear();
}

public static class MemoryCacheNew {
    private HashMap.softBitmap;
        return ref.get();
    }

    public void put(String id,Bitmap bitmap,int sampleSize){
        cache.put(id,new CachedBitmap(bitmap,sampleSize));
    }

    public void clear() {
        cache.clear();
    }



    private static class CachedBitmap {
        public SoftReference.softBitmap = new SoftReferenceirs();
}

public File getFile(String url){
    //I identify images by hashcode. Not a perfect solution,good for the demo.
    String filename=String.valueOf(url.hashCode());
    File f = new File(cacheDir,filename);
    return f;

}

public void clear(){
    File[] files=cacheDir.listFiles();
    for(File f:files)
        f.delete();
}

}

你这样称呼它:

imageLoader.displayImage(url,holder.image);

原文地址:https://www.jb51.cc/android/430594.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐