3

我已经实现了一个 ViewPager,它给了我一个 Out Of Memory 错误,我不知道为什么会这样。我有大约 11 张图片要展示,每张图片大约有 500 kb(磁盘大小),它们是 .jpg 格式。

这是代码:

public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bmw_gallery);

ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
}

private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
    R.drawable.bmw_1series_3door_wallpaper_01,
    R.drawable.bmw_1series_3door_wallpaper_02,
    R.drawable.bmw_1series_3door_wallpaper_03,
    R.drawable.bmw_1series_3door_wallpaper_04,
    R.drawable.bmw_1series_3door_wallpaper_05,
    R.drawable.bmw_1series_3door_wallpaper_06,
    R.drawable.bmw_1series_3door_wallpaper_07,
    R.drawable.bmw_1series_3door_wallpaper_08,
    R.drawable.bmw_1series_3door_wallpaper_09,
    R.drawable.bmw_1series_3door_wallpaper_11,
    R.drawable.bmw_1series_3door_wallpaper_12
};

@Override
public int getCount() {
  return mImages.length;
}

@Override
public boolean isViewFromObject(View view, Object object) {
  return view == ((ImageView) object);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
  Context context = MainActivity.this;
  ImageView imageView = new ImageView(context);
  imageView.setAdjustViewBounds(true);

  imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);

  imageView.setImageResource(mImages[position]);
  ((ViewPager) container).addView(imageView, 0);
  return imageView;
}


@Override
public void destroyItem(View collection, int position, Object o) {
    View view = (View)o;
    ((ViewPager) collection).removeView(view);
    view = null;
}


}



}

我做错了什么或我的代码中缺少什么?

4

3 回答 3

10

磁盘上的 500KB JPEG 图像将占用比这更多的堆空间。

例如,我这里有一张 494KB 的数码照片,分辨率为 1455 x 1029。如果我将其加载到 Android 应用程序中,它将消耗 1455x1029x3 = 4.3MB 的堆空间。如果您有 11 张具有相似特征的图像,它们加起来将消耗 > 40MB。大多数设备的每个进程都有 16-32MB 的堆空间。

如果你想发送 11 个可绘制资源(在这种情况下,可能是图像会让你被 BMW 起诉),你需要有更小的图像。

于 2013-02-23T18:56:55.277 回答
4

我在这里找到了解决方案:http: //developer.android.com/training/displaying-bitmaps/index.html 我刚刚在我的内部实现了 BitmapFun 项目。这样应用程序工作得非常好,我不再得到内存不足错误。

于 2013-03-01T08:31:50.033 回答
2

在 viewpager 中显示高分辨率图像时,我遇到了同样的问题。我已经搜索并应用了http://developer.android.com/training/displaying-bitmaps/index.html中给出的所有 android 位图解决方案,以下在链接中缓存机制。但它们都不起作用。任何地方都没有任何正确的解决方案。

Then I figured out that the problem is : I couldnt use the drawable folder structure right. I was keeping high resolution images in mdpi and hdpi folders . this cause android scale up the images to the ultra sizes. 100 kb image was causing 20 mb increase in memory thanks to the android monitor / memory section. so I have added these ultra resolution images to xxhdpi folder , then It was FIXED suddenly. then my image slider work flawlessly with high resolution images

于 2016-03-01T17:35:56.217 回答