Android : java.lang.OutOfMemoryError:

后端 未结 6 1683
太阳男子
太阳男子 2020-11-27 23:29

I developed an application that uses lots of images on Android.

There are lots of images present in drawable folder say more then 100, I am developing application fo

6条回答
  •  野性不改
    2020-11-28 00:00

    Replace:

    img.setBackgroundResource(R.drawable.dog_animation);
    

    By:

    img.setImageBitmap(decodeSampleBitmapFromResource(R.drawable.dog_animation, width, height));
    //dont forget to replace width and heigh by your imageview dimension
    

    An add:

    public static int calculateInSampleSize(
                BitmapFactory.Options options, int reqWidth, int reqHeight) {
    
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;
    
        if (height > reqHeight || width > reqWidth) {
    
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
    
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
    
        return inSampleSize;
    }
    

    and

    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
            int reqWidth, int reqHeight) {
    
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);
    
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }
    

    This is from: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

提交回复
热议问题