PagerView与图像崩溃

时间:2016-02-16 11:58:52

标签: android android-viewpager

我有PagerView,我想让它表现得像滑块一样能够显示大图像。问题是在刷了几张照片后它会崩溃。 stackoverflow上的另一个主题说我必须使用destroyItem方法,但不推荐使用它。

还有其他解决方法可以解决这个问题吗?

这是MainActivity

public class MainActivity extends AppCompatActivity {

ViewPager viewPager;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    viewPager = (ViewPager) findViewById(R.id.viewPager);
    CustomAdapter adapter = new CustomAdapter(MainActivity.this);
    viewPager.setAdapter(adapter);

    CirclePageIndicator circlePageIndicator = (CirclePageIndicator)findViewById(R.id.titles);
    circlePageIndicator.setViewPager(viewPager);

}
}

这里是适配器

public class CustomAdapter extends PagerAdapter {

    Context context;
    int[] imageId = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4, R.drawable.image5};

    public CustomAdapter(Context context){
        this.context = context;

    }


    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        // TODO Auto-generated method stub

        LayoutInflater inflater = ((Activity)context).getLayoutInflater();

        View viewItem = inflater.inflate(R.layout.image_item, container, false);
        ImageView imageView = (ImageView) viewItem.findViewById(R.id.imageView);
        imageView.setImageResource(imageId[position]);
        ((ViewPager)container).addView(viewItem);

        return viewItem;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return imageId.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        // TODO Auto-generated method stub

        return view == ((View)object);
    }

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

0 个答案:

没有答案