gridview滚动无法正确呈现(适当)

时间:2015-03-13 23:49:02

标签: android android-gridview custom-adapter

我对android gridview有一个奇怪的问题。我为gridview实现了一个自定义适配器,并从Rest API加载数据。根据来自服务器的布尔标志,gridview的设计发生了变化。 gridview有一个onScrollListener,它从api和reset适配器获取更多数据。问题是当我滚动太多(例如加载5倍)结果变得错误时,我的意思是渲染结果不是我所期望的。奇怪的是当我回来并向上滚动时,其他结果遗漏了一些部分(例如折扣盒部分消失了)。

我发布了自定义适配器类代码:

public class GridItemAdapter extends BaseAdapter {

private LayoutInflater inflater = null;
private Context mContext;
List<SimpleItem> SimpleItems;

public GridItemAdapter(Context mcontext, List<SimpleItem> SimpleItems) {
    this.mContext = mcontext;
    this.SimpleItems = SimpleItems;
    inflater = (LayoutInflater) this.mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return SimpleItems.size();
}

@Override
public Object getItem(int position) {
    return SimpleItems.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

public void addItems(List<SimpleItem> SimpleItems) {
    this.SimpleItems.addAll(SimpleItems);
    notifyDataSetChanged();
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.grid_item, null);
    }
    SimpleItem item = SimpleItems.get(position);
    TextView title = (TextView) convertView.findViewById(R.id.title);
    title.setText(item.getTitle());
    TextView territory = (TextView) convertView.findViewById(R.id.territory);
    territory.setText(item.getTitle());
    ImageView thumbnail = (ImageView) convertView.findViewById(R.id.thumbnail);
    Picasso.with(mContext)
            .load(item.getThumbnail())
            .placeholder(R.drawable.noimage)
            .into(thumbnail);
    TextView price = (TextView) convertView.findViewById(R.id.price);
    price.setText(item.getPrice());
    if (item.getHasDiscount()) {
        TextView discount = (TextView) convertView.findViewById(R.id.discount);
        discount.setText(item.getDiscount());
    } else {
        LinearLayout discountbox = (LinearLayout) convertView.findViewById(R.id.discountbox);
        price.setBackgroundColor(Color.parseColor("#07000000"));
        discountbox.setVisibility(View.GONE);
    }
    return convertView;
}

}

澄清示例:我希望在项目中可以看到折扣盒,但滚动时没有,并且不会出现discountbox。或者当它首先正确渲染时,当我向下滚动并返回时它会消失:(

如果有人帮助我,我将非常感激。我对网格视图回收有点怀疑,但是......

1 个答案:

答案 0 :(得分:1)

尝试对代码进行此更改并查看是否解决了问题,只是调用以设置折扣框可见

          if (item.getHasDiscount()) {
              TextView discount = (TextView) convertView.findViewById(R.id.discount);
              discountbox.setVisibility(View.VISIBLE);
              discount.setText(item.getDiscount());
          } else {
              LinearLayout discountbox = (LinearLayout) convertView.findViewById(R.id.discountbox);
              price.setBackgroundColor(Color.parseColor("#07000000"));
              discountbox.setVisibility(View.GONE);
          }