我正在尝试使用膨胀视图填充Android GridView,视图包含从ArrayList数据填充的ImageView和TextView。
一切都很好但是,当我滚动网格时,我的前7个项目正在重复。
namCont.setAdapter(new ImageAdapter(getApplicationContext()));
我的代码:
public class ImageAdapter extends BaseAdapter
{
private Context mContext;
public ImageAdapter(Context c)
{
mContext = c;
}
public int getCount()
{
return kat.namirnice.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View view;
ImageView imageView = null;
if (convertView == null)
{
view = LayoutInflater.from(mContext).inflate(R.layout.nam_item,null);
try
{
TextView textView = (TextView)view.findViewById(R.id.tekst);
imageView = (ImageView)view.findViewById(R.id.slika);
textView.setText(kat.namirnice.get(position).naziv);
Log.i(TAG, "\n position: " + position);
buf = new BufferedInputStream((assetManager.open("images/" + activKat_int + "/" + position + ".png")));
Bitmap bitmap = BitmapFactory.decodeStream(buf);
Drawable d = new BitmapDrawable(bitmap);
imageView.setImageDrawable(d);
buf.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
else
{
view = convertView;
}
return view;
}
答案 0 :(得分:6)
ListView中的视图被回收。所以最终,我想当你到达第8位时,它会回收它的第一个视图,而在你的代码中,你正在做的块view = convertView;
就是返回现有的回收视图。
相反,你需要这样做。
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.nam_item,
null);
}
try {
TextView textView = (TextView) convertView.findViewById(R.id.tekst);
ImageView imageView = (ImageView) convertView.findViewById(R.id.slika);
textView.setText(kat.namirnice.get(position).naziv);
Log.i(TAG, "\n position: " + position);
buf = new BufferedInputStream((assetManager.open("images/"
+ activKat_int + "/" + position + ".png")));
Bitmap bitmap = BitmapFactory.decodeStream(buf);
Drawable d = new BitmapDrawable(bitmap);
imageView.setImageDrawable(d);
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
return convertView;
}