永久填充ListView与图像?

时间:2016-04-05 16:01:53

标签: android image listview caching android-bitmap

我正在开发一个我有listview的应用程序。此列表视图中填充了从在线XML文件中提取的文本和图像。然而,它正确填充,无论何时滚动,屏幕上当前不存在的任何内容都会重新加载并重新计算位图的大小以进入列表视图。这导致滚动不那么流畅和烦人。如何让我的活动用图像填充列表视图并加载它们一次以留在那里?

ImageLoader的:

public class ImageLoader {

MemoryCache memoryCache = new MemoryCache();
FileCache fileCache;
private Map<ImageView, String> imageViews = Collections.synchronizedMap(new WeakHashMap<ImageView, String>());
ExecutorService executorService;

int size;
int placeholderpic;

public ImageLoader(Context context, int size, int placeholderpic) {
    fileCache = new FileCache(context);
    executorService = Executors.newFixedThreadPool(5);
    this.size = size;
    this.placeholderpic = placeholderpic;
}

public void displayImage(String url, ImageView imageView) {
    imageViews.put(imageView, url);
    Bitmap bitmap = memoryCache.get(url);
    if(bitmap != null)
        imageView.setImageBitmap(bitmap);
    else {
        queuePhoto(url, imageView);
        imageView.setImageResource(placeholderpic);
    }
}

private void queuePhoto(String url, ImageView imageView) {
    PhotoToLoad p = new PhotoToLoad(url, imageView);
    executorService.submit(new PhotosLoader(p));
}

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

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

    //from web
    try {
        Bitmap bitmap = null;
        URL imageUrl = new URL(url);
        HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
        conn.setConnectTimeout(30000);
        conn.setReadTimeout(30000);
        conn.setInstanceFollowRedirects(true);
        InputStream is=conn.getInputStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Throwable ex) {
        ex.printStackTrace();
        if(ex instanceof OutOfMemoryError)
            memoryCache.clear();
        return null;
    }
}

//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f) {
    try {
        //decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(new FileInputStream(f),null,o);

        //Find the correct scale value. It should be the power of 2.
        final int REQUIRED_SIZE = size;
        int width_tmp = o.outWidth, height_tmp=o.outHeight;
        int scale = 1;
        while(true){
            if(width_tmp/2 < REQUIRED_SIZE || height_tmp/2 < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }

        //decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    } catch (FileNotFoundException e) {}
    return null;
}

//Task for the queue
private class PhotoToLoad {
    public String url;
    public ImageView imageView;
    public PhotoToLoad(String u, ImageView i) {
        url = u;
        imageView = i;
    }
}

class PhotosLoader implements Runnable {
    PhotoToLoad photoToLoad;
    PhotosLoader(PhotoToLoad photoToLoad){
        this.photoToLoad = photoToLoad;
    }

    @Override
    public void run() {
        if(imageViewReused(photoToLoad))
            return;
        Bitmap bmp = getBitmap(photoToLoad.url);
        memoryCache.put(photoToLoad.url, bmp);
        if(imageViewReused(photoToLoad))
            return;
        BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad);
        Activity a = (Activity)photoToLoad.imageView.getContext();
        a.runOnUiThread(bd);
    }
}

boolean imageViewReused(PhotoToLoad photoToLoad) {
    String tag=imageViews.get(photoToLoad.imageView);
    if(tag == null || !tag.equals(photoToLoad.url))
        return true;
    return false;
}

//Used to display bitmap in the UI thread
class BitmapDisplayer implements Runnable {
    Bitmap bitmap;
    PhotoToLoad photoToLoad;

    public BitmapDisplayer(Bitmap b, PhotoToLoad p){
        bitmap = b; photoToLoad = p;
    }

    public void run() {
        if(imageViewReused(photoToLoad))
            return;
        if(bitmap != null)
            photoToLoad.imageView.setImageBitmap(bitmap);
        else
            photoToLoad.imageView.setImageResource(placeholderpic);
    }
}

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

ListView适配器:

public class LazyNewsAdapter extends BaseAdapter {

private Activity activity;
private ArrayList<News> listData;
private LayoutInflater inflater = null;

public LazyNewsAdapter(Activity activity, ArrayList<News> listData) {
    this.activity = activity;
    this.listData = listData;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

public int getCount() {
    return listData.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    News newsItem = listData.get(position);

    View view = convertView;
    if(convertView == null)
        view = inflater.inflate(R.layout.news_cell, null);

    TextView newsTitle = (TextView) view.findViewById(R.id.newsTitle);
    TextView newsDate = (TextView) view.findViewById(R.id.newsDate);
    ImageView image = (ImageView) view.findViewById(R.id.newsImage);

    newsTitle.setText(newsItem.getNewsTitle());
    newsDate.setText(newsItem.getNewsDate());
    String url = newsItem.getNewsImageUrl();

    ImageLoader imageLoader = new ImageLoader(activity, 600, R.drawable.placeholder);
    imageLoader.displayImage(url, image);

    return view;
}

3 个答案:

答案 0 :(得分:0)

尝试将在线数据保存到Array List变量。然后使用notifydatasetChange

将其加载到列表视图

答案 1 :(得分:0)

您必须使用缓存来处理这类事情。

请参阅Universal Image loader以高效方式加载图片。

您必须在一个活动中只有一个imageLoader实例,不要在每个getView中实例化它:

在onCreate中执行该行而不是getView:

    ImageLoader imageLoader = new ImageLoader(activity, 600, R.drawable.placeholder);

答案 2 :(得分:0)

在ListAdapter这里的视频教程中使用listview优化设置图像,这可能有助于您确保使用Glide设置图像,因为他们向前一步回收您的位图

https://www.youtube.com/watch?v=mKGoKnhN_Ys&index=91&list=PL1q3ROAofjeOUwh7lPBnGbg__DUodwLN7