gpt4 book ai didi

android - 从 Assets 填充 GridView 时出现问题

转载 作者:行者123 更新时间:2023-11-29 14:56:40 27 4
gpt4 key购买 nike

我正在尝试用膨胀 View 填充 Android GridView, View 有 ImageView 和 TextView,它们是从数据的 ArrayList 填充的。

一切都很好,但是,当我滚动网格时,我的前 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;
}

最佳答案

ListView 中的Views 被回收。所以最终,我猜当你到达位置 8 时它会回收它的第一个 View ,并且在你的代码中 block view = convertView; 你所做的就是返回现有的回收 View 。

相反,您需要这样做。

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;
}

关于android - 从 Assets 填充 GridView 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5204094/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com