引导页使用ViewPager遇到OutofMemoryError的解决方案

在开发中需要用到引导页, 用的Google ViewPager类, 采用的方式是在将图片设置于layout,最后加载所有的layout,但是由于加载的较多,由于加载的时候一不小心就报了OutofMemoryError。

layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@drawable/page01" 
     >
</LinearLayout>


 

最后优化一下,通过在instantiateItem中逐步加载layout的方式解决了该问题,

因为ViewPager自身有机制,回调destroyItem回收View资源。

PagerAdapter:

 
@Override
			public void destroyItem(ViewGroup container, int position,
					Object object) {
				// TODO Auto-generated method stub
				container.removeView((View)object);
			}

			@Override
			public Object instantiateItem(ViewGroup container, int position) {
				// TODO Auto-generated method stub
				LayoutInflater mLayoutInflater = getLayoutInflater();
				int resId=0;
				switch (position) {
				case 0:
					resId = R.layout.page01;
					break;
				case 1:
					resId = R.layout.page02;
					break;
				case 2:
					resId = R.layout.page03;
				break;
				case 3:
					resId = R.layout.page04;
				break;
				case 4:
					resId = R.layout.page05;
				break;
				case 5:
					resId = R.layout.page06;
				break;
				case 6:
					resId = R.layout.page07;
				break;
				default:
					break;
				}
				View view = mLayoutInflater.inflate(resId, null);
				container.addView(view, 0);
				return view;
			}

		};

你可能感兴趣的:(引导页使用ViewPager遇到OutofMemoryError的解决方案)