我已经实现了一个viewpager,它给了我一个内存不足的错误,我不知道为什么。我有大约11个图像显示,每个图像有大约500KB(磁盘大小)和他们是.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;
}
}
}
我做错了什么或者我的代码中缺少了什么?
最佳答案
磁盘上500KB的JPEG图像将占用比这多得多的堆空间。
例如,我这里有一张494KB的数码照片,分辨率为1455x 1029。如果我将其加载到Android应用程序中,它将消耗1455x1029x3=4.3MB的堆空间。如果您有11个具有类似特征的图像,它们的合并将消耗>40MB。大多数设备每个进程有16-32MB的堆空间。
如果你想运送11个可提取的资源(在这种情况下,可能的图像会让你被宝马起诉遗忘),你需要有更小的图像。