标签:
以前写viewpager的时候,总是先把view用循环创建出来.然后添加到集合里面,创建adapter的时候,直接把这个集合传递过去,这样的方法一直没什么问题.直到有一天写的一个简单的viewpager却在三星手机中挂掉之后,就开始正视自己了.这样写是不行的,于是有了下面的这些代码:
activity:
package com.bill3g.saferun; import java.util.ArrayList; import java.util.List; import android.R.integer; import android.content.Context; import android.os.Bundle; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBarActivity; import android.view.View; import android.widget.ImageView; public class MainActivity extends ActionBarActivity { private Context context; private ViewPager vp_main; private MyPagerAdapter myPagerAdapter; private int[] imageRes = { R.drawable.tab1, R.drawable.tab2, R.drawable.tab3, R.drawable.tab4, R.drawable.tab5, R.drawable.tab6, R.drawable.tab7, R.drawable.tab8, R.drawable.tab9, R.drawable.tab10, R.drawable.tab11, R.drawable.tab12 }; private List<Integer> imageList = new ArrayList<Integer>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); context = this; initView(); initEvent(); } private void initEvent() { getViewList(); myPagerAdapter = new MyPagerAdapter(context, imageList); vp_main.setAdapter(myPagerAdapter); } private void initView() { vp_main = (ViewPager) findViewById(R.id.vp_main); } private void getViewList() { for (int i = 0; i < imageRes.length; i++) { imageList.add(imageRes[i]); } } }
package com.bill3g.saferun; import java.util.List; import android.content.Context; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; public class MyPagerAdapter extends PagerAdapter { private Context context; private List<Integer> list; public MyPagerAdapter(Context context, List<Integer> list) { this.context = context; this.list = list; } // 我们在销毁不必要的视图的时候,就可以直接把object转换成view然后移除,这个object就是instantiateItem的时候,返回的东西 @Override public void destroyItem(ViewGroup container, int position, Object object) { ((ViewPager) container).removeView((View) object); } // 在生成该视图的时候,进行视图的创建,然后设置 @Override public Object instantiateItem(ViewGroup container, int position) { ImageView imageView = new ImageView(context); imageView.setBackgroundResource(list.get(position)); ((ViewPager) container).addView(imageView); return imageView;// 返回我们刚刚添加的那个视图 } @Override public int getCount() { return list.size(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } }
android viewpager outofmemery问题解决
标签:
原文地址:http://blog.csdn.net/u010399316/article/details/46551215