I wrote a short demo for my answer which you can see here.
Example:
When you're ready, you can then use your data source (not your adapter, not your listview) to find the products that have a quantity > 0.
public List<Product> getBasket() {
List<Product> basket = new ArrayList<>();
for (Product product : productList) {
if (product.quantity > 0) {
basket.add(product);
}
}
return basket;
}
Your adapter has one job: to create/bind Views to data, it does not need to do more.
initial answer without demo:
If you update the item views directly, you won't be able to fetch all the items with a positive number later because these updated values are only stored in the views, and not in some data structure you can iterate over.
This is why you shouldn't update item views directly, but instead use a callback when the plus/minus button is clicked, modify the underlying dataset, and call adapter.notifyDatasetChanged()
to update the ListView/RecyclerView again.
Pass a callback to your adapter:
public interface ItemInteraction {
void onPlusButtonClick(long id);
void onMinusButtonClick(long id);
}
which you can use by setting it as the callback for click listeners on the relevant views. The ID can be anything so long as it can uniquely identify the data item represented by a list view row.
final long id = item.getId();
plusButtonView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick() {
callback.onPlusButtonClick(id);
}
});
An example is given in this similar question where OP wanted to show or hide a star (indicating favourite) for a list of songs here.
Another explanation of how adapter-like views are designed to be used.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…