12

我有一个应用程序显示来自服务器的图像。现在我懒加载我的图片。所以最初我在图像完成加载时显示一个进度条我通过将其visibility属性设置为来删除进度条View.INVISIBLE并显示图像。这是我用于图像的布局文件

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center" >

     <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_gravity="center"
            android:contentDescription="@string/app_name"
            android:scaleType="centerInside"
            android:src="@drawable/ic_launcher" />

    <RelativeLayout
        android:id="@+id/loading_layout"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="@android:color/white" >

        <ProgressBar
            android:id="@+id/progressBar1"
            style="?android:attr/progressBarStyleSmall"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:background="@android:color/white" />
    </RelativeLayout>

</FrameLayout>

问题 当进度条消失时,屏幕上显示的图像已损坏。喜欢这张图片

当我刷新列表时,从缓存目录加载的图像,当它们显示在屏幕上时,它们显示正确,没有任何损坏。

在此处输入图像描述

我用来延迟加载图像的 ImageLoader 类

public class ImageLoader {
    // @@ JUST FOR THIS PROJECT
    BaseAdapter mAdapter;
    // @@
    MemoryCache memoryCache = new MemoryCache();
    FileCache fileCache;
    private Map<ImageView, String> imageViews = Collections
            .synchronizedMap(new WeakHashMap<ImageView, String>());
    ExecutorService executorService;

    boolean addRoundCournerAndStroke = false;
    boolean scale = false;

    boolean localfile = false;
    int default_image;

    public ImageLoader(Context context, boolean flag, boolean scale,
            boolean localfile) {
        fileCache = new FileCache(context);
        this.addRoundCournerAndStroke = flag;
        executorService = Executors.newFixedThreadPool(5);
        this.scale = scale;
        this.localfile = localfile;

    }

    public ImageLoader(Context context, boolean flag, boolean scale,
            boolean localfile, int default_image_id) {
        this(context, flag, scale, localfile);
        this.default_image = default_image_id;
    }

    public ImageLoader(Context context, boolean flag, boolean scale,
            boolean localfile, int default_image_id, BaseAdapter adapter) {
        this(context, flag, scale, localfile);
        this.default_image = default_image_id;
        this.mAdapter = adapter;
    }

    public void DisplayImage(String url, ImageView imageView) {
        imageViews.put(imageView, url);
        Bitmap bitmap = memoryCache.get(url);
        if (bitmap != null) {
            changeProgressBarVisibilty(imageView, false);
            imageView.setImageBitmap(bitmap);
        }

        else {
            queuePhoto(url, imageView);
            imageView.setImageResource(this.default_image);
        }
    }

    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 = null;
        if (localfile)
            f = new File(url);
        else
            f = fileCache.getFile(url);

        // Log.d("bytes", "decode");
        // 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);
            // //Log.d("bytes", "decode");
            return bitmap;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private Bitmap decodeFileWithoutScaling(File f) {
        try {
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = 1;
            //o2.inPurgeable = true;
            if (this.localfile)
                return BitmapFactory.decodeFile(f.getAbsolutePath(), o2);
            else
                return BitmapFactory.decodeStream(new FileInputStream(f), null,
                        o2);
        } catch (FileNotFoundException e) {
        }
        return null;
    }

    private Bitmap decodeFile(File f) {

        if (this.scale) {
            return decodeFileWithScalling(f);
        } else {
            return decodeFileWithoutScaling(f);
        }
    }

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

        //  o.inPurgeable = true;
            if (this.localfile)
                BitmapFactory.decodeFile(f.getAbsolutePath(), o);
            else
                BitmapFactory.decodeStream(new FileInputStream(f), null, o);

            // Find the correct scale value. It should be the power of 2.
            final int REQUIRED_SIZE = 70;
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            // Log.d("width", width_tmp + "");
            // Log.d("height", height_tmp + "");
            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;
        //  o2.inPurgeable = true;
            // Log.d("after shave width", o2.outWidth + "");
            // Log.d("after shave height", o2.outHeight + "");
            if (this.localfile)
                return BitmapFactory.decodeFile(f.getAbsolutePath(), o2);
            else
                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;
        }

        public void run() {
            if (imageViewReused(photoToLoad)) {
                return;
            }

            Bitmap bmp = getBitmap(photoToLoad.url);

            // if (addRoundCournerAndStroke) {
            // // bmp = ImageHelper.rotateAndFrame(bmp, 10);
            // bmp = ImageHelper.getRoundedCornerBitmap(bmp, 10);
            // }

            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;
            changeProgressBarVisibilty(photoToLoad.imageView, false);
            if (bitmap != null) {
                photoToLoad.imageView.setImageBitmap(bitmap);


            } else {
                photoToLoad.imageView
                        .setImageResource(ImageLoader.this.default_image);

            }
            if (mAdapter != null) {
                mAdapter.notifyDataSetChanged();
            }

        }
    }

    private void changeProgressBarVisibilty(ImageView image, boolean visible) {
        ViewGroup layout = (ViewGroup) image.getParent();

        try {
            View v = layout.findViewById(R.id.loading_layout);
            v.setVisibility(visible ? View.VISIBLE : View.GONE);
        } catch (Exception ex) {
            ex.printStackTrace();
        }



    }



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

}
4

3 回答 3

5

尝试使用 ProgressDialog 而不是 Progressbar。ProgressDialog 也可以使用进度条。ProgressDialog 不是 XML 类型。因此您可以使用 show() 或 dismiss() 方法。也许它没有这个问题。我认为这个问题来自RelativeLayout。如果您使用 ProgressBar Visiblity ,RelativeLayout 仍然可见(但没有背景)。RelativeLayout 也有任何项目。我猜空布局给你带来了腐败。使用 ProgressDialog 是最好的..

于 2012-07-31T11:10:59.693 回答
3

损坏的图像显示损坏的 JPEG 伪影。

您的问题可能来自该 BitmapFactory.decodeStream方法。并非所有 JPEG 都针对动态解码(“渐进式”)进行了优化,因此在正确解码之前,它们可能需要作为一个整体可用。通常,非渐进式图像可以自上而下解码,但这可能不适用于所有文件,或者解码器可能有一些缺陷会阻止这种情况。

另一方面,如果稍后从缓存文件中获取图像,BitmapFactory.decodeFile则使用不需要关心流数据并且可以随机访问图像文件以解码 JPEG。如果您在加载图像时不需要逐行显示更新,我建议您消除此代码路径并始终在解码前下载整个图像。

于 2012-08-03T16:27:30.607 回答
-1

我认为您可以尝试将可见性设置为View.GONE,因为当您设置View.INVISIBLEView 时,该位置仍然存在,并且就像 Tae 所说的那样,RelativeLayout 可能存在一些问题。

干杯

于 2012-08-03T13:14:31.897 回答