Does a replacement for Gallery widget with View recycling exist?

后端 未结 5 562
情深已故
情深已故 2020-12-04 22:40

The default Gallery widget on Android does not recycle views - everytime the view for a new position is called the widget always calls the getView method of the

5条回答
  •  余生分开走
    2020-12-04 23:15

    Another quicker WorkAround for the OutOfMemory Issues, is to try/catch the code where you decode the image and if the OutOfMemory-exception is thrown, you try to decode it with smaller Resolution again..

    something like this:

    private static Bitmap decodeFile(File f, int size, int suggestedScale) {
    
        int scale = 1;
        Bitmap bmp = null;
        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.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
    
            if(suggestedScale > 0)
                scale = suggestedScale;
            else {
                if (width_tmp >= height_tmp) {
                    scale = Math.round((float)(width_tmp) / size);
                } else {
                    scale = Math.round((float)(height_tmp) / size);
                }
            }
    
            if(scale < 2)
                return BitmapFactory.decodeFile(f.getPath()); 
    
            Debug.i(TAG, "width: " + width_tmp + "  height: " + height_tmp + "  scale: " + scale);
    
    
            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            bmp = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
        } catch (FileNotFoundException e) {
    
        } catch(OutOfMemoryError e) {
            Debug.i(TAG, "we retry it cause of an OutOfMemoryException");
            return decodeFile(f, size, scale+1);
        } catch(Exception e){
            Debug.w(TAG, e);
        }
        return bmp;
    }
    

    Ofcourse it is now possible, that you will see different resolutions of the same picture at different times - But at least your Gallery will not crash anymore and you allways show the highest resolution you can.

提交回复
热议问题