如何动态地将唯一图像加载到每个gridview元素

时间:2014-03-01 16:48:53

标签: android gridview image-loading

我想为每个gridview元素加载唯一的图像,但它只加载gridview的所有元素的最后一个图像。我该如何解决?我的示例图像名称类似于a50.jpg

其中5是我的类别编号,0是此类别中的元素编号,因此当您查看此内容时,您将看到我想要获取类别的walue并加载这些类别元素的所有图像。

这是我的代码:

public class TowarAdapter extends ArrayAdapter<Towar> {
    private List<Towar> items;
    private Activity context;

    public TowarAdapter(Activity context, int resource, List<Towar> items) {
        super(context, resource);

        this.items = items;
        this.context = context;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return items.size();
    }

    @Override
    public Towar getItem(int position) {
        // TODO Auto-generated method stub
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    static class ViewHolder {
        ImageView ivTowar;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder view;

        LayoutInflater inflator = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        if (convertView == null) {
            view = new ViewHolder();
            convertView = inflator.inflate(R.layout.element, null);

            view.ivTowar = (ImageView) convertView.findViewById(R.id.ivTowar);

            convertView.setTag(view);
        }
        else {
            view = (ViewHolder) convertView.getTag();
        }

        for (int i = 0; i < items.size(); i++) {
            String s = Integer.valueOf(items.get(position).Kat_id).toString();
            int resourceId = context.getResources().getIdentifier("a" + s + i,
                    "drawable", context.getPackageName());
            view.ivTowar.setImageResource(resourceId);
        }
        return convertView;
    }
}

Towar.class:

public class Towar {
    public int Tow_id;
    public int Kat_id;
    public String Tow_nazwa;
    public String Tow_opis;
    public String Tow_producent;
    public String Tow_nr_czesci;
    public float Tow_cena;
    public int Tow_ilosc;
    public String Tow_specyfikacja;
    public Kategoria kategoria;

    public Towar() {

    }

    setters and
    getters

}

1 个答案:

答案 0 :(得分:1)

您可以使用索引即位置并从列表中获取项目。

将所有图像ID存储在列表或数组中。将列表或数组传递给适配器类的构造函数。

int[] myImageList = new int[]{R.drawable.thingOne, R.drawable.thingTwo};

将数组传递给适配器类

的构造函数
in[] imgid;
public TowarAdapter(Activity context, int resource, int[] imgid)        
{
   super(context, resource);
  this.imgid = imgid

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

然后在getView

 view.ivTowar.setImageResouce(imgid[i]);