创建的每个项目都是Product类型的对象,具有名称,价格和数量。碰巧当我试图在gridview中接收每个项目的位置时,我总是得到视图的第一项。在发布我的问题之前,我看了几个其他的帖子,看起来我正在做的一切正确,以便如何使用标签。
我有
@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();
}
当我运行模拟器现在重要的是我点击的项目总是得到这个结果:
如果您需要查看更多代码,请告诉我,我会发布它。提前谢谢你们。
答案 0 :(得分: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)
,这不再是您点击的相同视图。
您点击的视图是removeProduct()