Android Outofmemory drawable

Ken*_*ett 8 android out-of-memory

这是我的viewpager数组中的drawable,当我运行它时,我会导致内存不足错误,有没有办法减少图像大小等?我做了很多搜索,但我也不能使用它们..请帮助...

GalImages = new int[] { R.drawable.tutorials_01_android_en,R.drawable.tutorials_02_android_en,R.drawable.tutorials_03_android_en,R.drawable.tutorials_04};break

@Override
public Object instantiateItem(ViewGroup container, int position) {

    ImageView imageView = new ImageView(context);
    final int temp = position;
    imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
    imageView.setImageResource(GalImages[position]);

    ((ViewPager) container).addView(imageView, 0);
    imageView.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {}
    });
    return imageView;
}
Run Code Online (Sandbox Code Playgroud)

Qua*_*Ali 19

它是一个已知的bug,它不是因为大文件.由于Android缓存Drawables,因此在使用少量图像后内存不足.但我通过跳过Android默认缓存系统找到了它的替代方式.

Soultion:在Assets中创建一个drawable文件夹,并将图像移动到资源中的"drawable"文件夹,并使用以下函数获取BitmapDrawable

public static Drawable getAssetImage(Context context, String filename) throws IOException {
    AssetManager assets = context.getResources().getAssets();
    InputStream buffer = new BufferedInputStream((assets.open("drawable/" + filename + ".png")));
    Bitmap bitmap = BitmapFactory.decodeStream(buffer);
    return new BitmapDrawable(context.getResources(), bitmap);
}
Run Code Online (Sandbox Code Playgroud)

参考:https://stackoverflow.com/posts/6116316/revisions

另外,在清单文件中添加以下行

android:largeHeap="true"
Run Code Online (Sandbox Code Playgroud)

  • 不要用android解决这类问题:largeHeap ="true",这不是解决方案 (5认同)

Muh*_*mad 12

尝试将您的drawables从较低的MPI移动到HDPI或更高的维度文件夹,如XHDPI,具体取决于您的分辨率.

我的图片尺寸范围为400-800像素.我将我的drawables存储在我的Galaxy S4上抛出OutOfMemory的MDPI中.我把它们移到了HDPI,它解决了这个问题.