【问题标题】:I'm always receiving the same item我总是收到相同的物品
【发布时间】:2016-03-31 21:28:07
【问题描述】:

创建的每个项目都是具有名称、价格和数量的 Product 类型的对象。碰巧当我试图在网格视图中接收每个项目的位置时,我总是得到视图的第一个项目。在发布我的问题之前,我看了其他几篇帖子,似乎我为了如何使用标签所做的一切都是正确的。

我有

@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
    if (convertView == null || (convertView.getTag() == null)) {
        convertView = inflater.inflate(R.layout.listview_values, parent, false);
        holder = new ViewHolder();
        holder.productName = (TextView) convertView.findViewById(R.id.textViewList1);
        holder.productQuantity = (EditText) convertView.findViewById(R.id.EditTextList2);
        holder.productPrice = (TextView) convertView.findViewById(R.id.textViewList3);
        holder.removeProduct = (ImageButton) convertView.findViewById(R.id.removeProduct);
    }
    else {
        holder = (ViewHolder) convertView.getTag();
    }
    convertView.setTag(holder);
    holder.productName.setText(products.get(position).getProductName());
    holder.productQuantity.setText(String.valueOf(products.get(position).getProductQuantity()) + " Un.");
    holder.productPrice.setText(String.valueOf(products.get(position).getProductPrice())+ " €");
    holder.removeProduct.setTag(new Integer(position));

    return convertView;
}

 public void removeProduct(View v) {

    ImageButton removeProduct = (ImageButton) findViewById(R.id.removeProduct);
    Integer position = (Integer) removeProduct.getTag();

    Product p1 = (Product) adapter.getItem(position);

    Toast toast = Toast.makeText(this,"You want to remove the item: "+ position +" with the product name: "+ p1.getProductName() + " , quantity: "+ p1.getProductQuantity()
            + " , price: " + p1.getProductPrice(),Toast.LENGTH_LONG); toast.show();
}

当我现在运行模拟器时,无论我点击什么项目,我总是得到这个结果:

如果您需要查看更多代码,请告诉我,我会发布。提前谢谢你们。

【问题讨论】:

  • 你可以试试这个:Integer position = (Integer) v.getTag();
  • 它有效,但我不明白,你能解释一下吗? ...顺便谢谢
  • 当您执行 findViewById 时,您总是从同一个对象获取标签,因为您必须从参数“v”中获取标签

标签: android gridview tags baseadapter


【解决方案1】:

将您的 removeProduct() 更改为 -

public void removeProduct(View v) {    
    Integer position = (Integer) v.getTag();

    Product p1 = (Product) adapter.getItem(position);

    Toast toast = Toast.makeText(this,"You want to remove the item: "+ position +" with the product name: "+ p1.getProductName() + " , quantity: "+ p1.getProductQuantity()
            + " , price: " + p1.getProductPrice(),Toast.LENGTH_LONG); toast.show();
}

原因是因为你再次初始化你的视图

  ImageButton removeProduct = (ImageButton) findViewById(R.id.removeProduct)

这不再是您单击的同一个视图。 你点击的view就是removeProduct()传入的参数

【讨论】:

  • 那为什么我收到的是 removeProduct 的标签而不是 convertView 对象的标签?
  • "View v" 是同一个 convertView 对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 2015-10-17
  • 1970-01-01
  • 2013-12-27
  • 1970-01-01
  • 2021-01-10
  • 2018-08-13
相关资源
最近更新 更多