如何修复GridView中的内存泄漏?

时间:2013-12-22 16:18:00

标签: android gridview memory-leaks

每次旋转GridView后内存使用量都在增加......

在GridView上设置适配器:

        gridview = (GridView) findViewById(R.id.grid);
        gridview.setAdapter(new MenuAdapter(getApplicationContext(), width, height, density, gridview));
        gridview.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                Toast.makeText(getApplicationContext(), Integer.toString(position), Toast.LENGTH_SHORT).show();
            }
        });

适配器getView部分:

    public View getView(int position, View convertView, ViewGroup parent) {


    if (convertView == null) {

        gridView = new View(context);
        gridView = inflater.inflate(R.layout.menu_item, null);          

    } else {
        gridView = (View) convertView;
    }


    btn_ = (LinearLayout) gridView.findViewById(R.id.btn);
    textView = (TextView) gridView.findViewById(R.id.menuItem_txt);
    imageView = (ImageButton) gridView.findViewById(R.id.menuItem_img);

    btn_.setBackgroundColor(back_color[position]);      

    textView.setText(menuValues[position]);
    textView.setTextColor(txt_color[position]);
    textView.setTypeface(font);

    imageView.setScaleType(ImageButton.ScaleType.CENTER_CROP);
    imageView.setFocusable(false);
    imageView.setClickable(false);
    imageView.setAdjustViewBounds(true);
    imageView.setColorFilter(img_color[position]);
    imageView.setImageResource(img[position]);


    return gridView;
}

在“else {}”和“return”语句之间删除部分之后没有内存增加,所以我想问题是删除代码中的某个地方......?

1 个答案:

答案 0 :(得分:0)

删除此

 gridView = new View(context); // not required

使用ViewHolder模式

http://developer.android.com/training/improving-layouts/smooth-scrolling.html

static class ViewHolder
{
TextView tv;
ImageView iv;
LinearLayout b;
}

getView更改为

@Override
public View getView(int position, View convertView, ViewGroup parent) {
 ViewHolder holder;

if (convertView == null) {
    convertView = inflater.inflate(R.layout.menu_item, null);     
    holder = new ViewHolder();
    holder.iv = (ImageButton) convertView.findViewById(R.id.menuItem_img);   
    holder.b = (LinearLayout) convertView.findViewById(R.id.btn);
    holder.tv = (TextView) convertView.findViewById(R.id.menuItem_txt);
    convertView.setTag(holder);
} else {
     holder = (ViewHolder) convertView.getTag();
}


holder.b.setBackgroundColor(back_color[position]);      
holder.tv.setText(menuValues[position]);
holder.tv.setTextColor(txt_color[position]);
holder.tv.setTypeface(font);

holder.iv.setScaleType(ImageButton.ScaleType.CENTER_CROP);
holder.iv.setFocusable(false);
holder.iv.setClickable(false);
holder.iv.setAdjustViewBounds(true);
holder.iv.setColorFilter(img_color[position]);
holder.iv.setImageResource(img[position]);


return convertView;
}