我有一个列表包含图像,每次用户点击图像然后在网格视图上图像将显示在网格视图上,这部分我已经完成并且它正在工作。 问题是当用户开始向上/向下滚动时,网格上的所有先前图像开始在不同的地方显示。我猜我的适配器里面的getView函数有问题
public class GridAdapter extends BaseAdapter{
Context mContext;
public GridAdapter(Context con){
mContext = con;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return Globals.obsImageMatrix.size();
}
@Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup arg2) {
if(convertView==null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.grid_image, null);
Holder.image =(ImageView) convertView.findViewById(R.id.obsImage);
// Holder.image.setImageResource(R.drawable.blank);
}
Holder.image =(ImageView) convertView.findViewById(R.id.obsImage);
Holder.image.setImageResource(Globals.obsImageMatrix.get(position));
return convertView;
}
public static class Holder{
public static ImageView image;
}
}
Globals.obsImageMatrix是一个矩阵,它的大小与网格本身一样,包含网格图像。
答案 0 :(得分:3)
您没有正确使用ViewHolder。试试这个:
@Override
public View getView(final int position, View convertView, ViewGroup arg2) {
ViewHolder holder = null;
if(convertView==null){
LayoutInflater vi = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.grid_image, null);
holder = new ViewHolder();
holder.image =(ImageView) convertView.findViewById(R.id.obsImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.image.setImageResource(Globals.obsImageMatrix.get(position));
return convertView;
}
public static class Holder{
public ImageView image;
}
您必须阅读有关viewHolders的更多信息才能理解此模式。 SO和google上有很多帖子。
希望这会对你有所帮助
答案 1 :(得分:0)
改为使用它作为LayoutInflater:
Context mContext;
Private LayoutInflater mInflater;
public GridAdapter(Context con){
mContext = con;
mInflater = LayoutInflater.from(con);
}
在你的getView()中:
@Override
public View getView(final int position, View convertView, ViewGroup arg2) {
ViewHolder holder;
if(convertView==null){
convertView = mInflater.inflate(R.layout.grid_image, null);
holder = new ViewHolder();
holder.image =(ImageView) convertView.findViewById(R.id.obsImage);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.image.setImageResource(Globals.obsImageMatrix.get(position));
return convertView;
}
static class Holder{
ImageView image;
}