GridView中的setImageResource会产生漏洞

时间:2012-06-28 11:21:12

标签: android gridview layout-inflater

大家好,我有问题。 我想用自定义Loyout做一个GridView,所以我用layoutInflater做了这个:

private ImageView prima;
private ImageView seconda;

public View getView(int position, View convertView, ViewGroup parent) {
        View v;
        if (convertView == null) {

            LayoutInflater li = getLayoutInflater();
            v = li.inflate(R.layout.icon, null);

            Display display = getWindowManager().getDefaultDisplay();
            int width = display.getWidth();

            prima = (ImageView) v.findViewById(R.id.imageView1);
            prima.getLayoutParams().height = width / 3;
            prima.getLayoutParams().width = width / 3;
            seconda = (ImageView) v.findViewById(R.id.imageView2);
            seconda.getLayoutParams().height = width / 3;
            seconda.getLayoutParams().width = width / 3;

            v.setLayoutParams(new GridView.LayoutParams(width / 3, width / 3));
            v.setPadding(0, 0, 0, 0);
        } else {
            v = convertView;
        }

        prima.setImageResource(mThumbIds[position]); //mThumbIds[] is an array with R.drawable.vip_0_mini, R.drawable.a_1, R.drawable.b_2, R.drawable.c_3 .....
        return v;

    };

当我运行我的应用程序时,图像是随机排列的,并且有许多黑色空间没有图像。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

您的ViewconvertView没有关联。 尝试ViewHolder concept这样:

public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder v;
        if (convertView == null) {

            LayoutInflater li = getLayoutInflater();
            convertView  = li.inflate(R.layout.icon, null);

            Display display = getWindowManager().getDefaultDisplay();
            int width = display.getWidth();

            v = new ViewHolder();
            v.prima = (ImageView) convertView .findViewById(R.id.imageView1);
            v.prima.getLayoutParams().height = width / 3;
            v.prima.getLayoutParams().width = width / 3;
            v.seconda = (ImageView) convertView .findViewById(R.id.imageView2);
            v.seconda.getLayoutParams().height = width / 3;
            v.seconda.getLayoutParams().width = width / 3;

            convertView .setLayoutParams(new GridView.LayoutParams(width / 3, width / 3));
            convertView .setPadding(0, 0, 0, 0);
            convertView.setTag(v);
        } else {
            v = (ViewHolder)convertView.getTag();
        }

        v.prima.setImageResource(mThumbIds[position]); //mThumbIds[] is an array with R.drawable.vip_0_mini, R.drawable.a_1, R.drawable.b_2, R.drawable.c_3 .....

         //v.seconda
        return convertView;

    };

class ViewHolder{
    ImageView prima;
    ImageView seconda;
}

答案 1 :(得分:0)

您忘了将图片应用到

    seconda = (ImageView) v.findViewById(R.id.imageView2);

    prima.setImageResource(....);