我无法理解如何让每个list_item的按钮只修改它被单击的行。我一直在寻找通过使用ViewHolder类的不同职位并实现setTag()/ getTag()方法,但我无法准确理解如何在代码中使用所有这些。我想要的按钮是增加一个TextView中数字的值,并减少另一个TextView中另一个数字的值,然后更新数据库。到目前为止,当我点击按钮时,它会更改屏幕上任何list_item的值,而不是该按钮所属的list_item,并且只能使用一次。我知道我可能只需要通过传递当前视图来告诉按钮哪个视图改变,但我只是感到困惑。 这里是我到目前为止的代码:SetOnClickListener()to list_item中的按钮使用CursorAdapter
package com.example.ms.inventory_app;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.TextView;
import com.example.ms.inventory_app.data.ProductContract.ProductEntry;
public class ProductCursorAdapter extends CursorAdapter {
private String mSold, mQuantity;
private TextView mQuantityTextView, mSoldTextView;
private Button mButton;
public ProductCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView nameTextView = (TextView) view.findViewById(R.id.product_name);
String name = cursor.getString(cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_NAME));
nameTextView.setText(name);
TextView priceTextView = (TextView) view.findViewById(R.id.product_price);
String price = Integer.toString(cursor.getInt(cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_PRICE)));
priceTextView.setText(price);
mQuantityTextView = (TextView) view.findViewById(R.id.product_quantity);
mQuantity = Integer.toString(cursor.getInt(cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_QUANTITY)));
mQuantityTextView.setText(mQuantity);
mSoldTextView = (TextView) view.findViewById(R.id.product_sold);
mSold = Integer.toString(cursor.getInt(cursor.getColumnIndex(ProductEntry.COLUMN_PRODUCT_SOLD)));
mSoldTextView.setText(mSold);
mButton = (Button) view.findViewById(R.id.sale_button);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int currentSold = Integer.parseInt(mSold);
int currentQuantity = Integer.parseInt(mQuantity);
currentSold+=1;
currentQuantity-=1;
mSoldTextView.setText(Integer.toString(currentSold));
mQuantityTextView.setText(Integer.toString(currentQuantity));
}
});
}
}
预先感谢任何帮助