ViewPager上的位图导致内存泄漏

时间:2014-07-06 11:15:08

标签: android image android-viewpager out-of-memory

我正在使用带有PagerAdapter的ViewPager来显示一个视图,其中包含两个ImageView(一个带有大图像,一个带有一个小图标)和一个TextView。当您在ViewPager上“翻页”时,堆会一直在增长,直到它在OutOfMemoryError(192MB)上崩溃。 GC无法释放空间。即使我切换活动,堆也会保持其大小。 以下是适配器的部分,如果您需要代码的其他部分,请告诉我。 destroyItem方法假设清除视图并释放内存,但事实并非如此。 “TicketViewHolder.image”是包含稍大图像的ImageView。 下一步是重新缩放图像,但这不是主要问题。

private class TicketViewHolder {
    private TextView name;
    private ImageView image;
    private ImageView vSign;
}

@Override
public Object instantiateItem(ViewGroup container, final int position) {
    TicketViewHolder holder = null;
    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    View view = mInflater.inflate(R.layout.ticket_page, container, false);
    holder = new TicketViewHolder();
    holder.name = (TextView) view.findViewById(R.id.ticket_name);
    holder.image = (ImageView) view.findViewById(R.id.ticket_image);
    holder.vSign = (ImageView) view.findViewById(R.id.ticket_v);

    Word word = getItem(position);
    holder.name.setText(word.getName());

    holder.image.setImageResource(word.getImageID());
    holder.image.setOnClickListener(onImageClickListener);

    holder.image.setTag(position);
    holder.vSign.setTag(position);
    holder.vSign.setOnClickListener(onPositiveProductionClickListener);

    if (word.isCorrect()) {
        holder.vSign.setImageResource(R.drawable.v_green);
    } else {
        holder.vSign.setImageResource(R.drawable.v_red);
    }

    container.addView(view, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    jazzyViewPager.setObjectForPosition(view, position);
    return view;
}

@Override
public void destroyItem(View collection, int position, Object obj) {
    Log.d("DESTROY", "destroying view at position " + position);
    View view = (View) obj;
    ((ViewPager) collection).removeView(view);
    view = null;
}

2 个答案:

答案 0 :(得分:1)

在ViewPagerAdapter类中尝试此代码

   private int getPagesBack() {
        return currentPosition - 3;
    }

    private int getPagesForward() {
        return currentPosition + 3;
    }

    private boolean canDestroy(int position) {
        return !(position > getPagesBack() && position < getPagesForward());
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
    if(canDestroy(position)){
            Log.d(TAG, "destorying position: " + position);
            View v = (View) object;
            container.removeView((View) object);
    }
    }

答案 1 :(得分:0)

我认为这是一个普遍的问题,但显然不是。它与使用 - JazzyViewPager的自定义ViewPager有关,我找到了solution