Anoop Kanyan
Anoop Kanyan

Reputation: 618

Android RecyclerView, alter view based on OnClick.

I have implemented a RecyclerView. I wrote a custom adapter for it. It renders a list of cards with some textView and buttons. I have two buttons inside each card, a plusButton and a minusButton and I want to change the values inside textViews according to click on these Buttons. It does work correctly, but when we scroll down, along with the card which was clicked, another card's textView also gets updated. I know it's happening because the objects are recycled and I use the position in my code. How do I stop it from updating the other cards? Here is the code:

 @Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {

    final Product product = productList.get(position);
    holder.productName.setText(product.getName());
    holder.productPrice.setText("$ " + product.getPrice().toString());


    holder.productImage.setImageUrl(product.getImage(), holder.imageLoader);

    //load image and actions for buttons

    array = new int[productList.size()];

    holder.plusButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            productList.get(position).setTotal_on_hand(1);
            holder.productQty.setText(product.getTotal_on_hand());
            this.notify();


            Product pr = productList.get(position);
            int pos;
            if (passList.contains(pr)) {
                pos = passList.indexOf(pr);
                array[pos]++;
                priceTotal = priceTotal + pr.getPrice().floatValue();
                qtyTotal++;
                holder.productQty.setText(Integer.toString(array[pos]));
            } else {
                passList.add(pr);
                pos = passList.indexOf(pr);
                array[pos] = 1;
                qtyTotal++;
                priceTotal = priceTotal + pr.getPrice().floatValue();
                holder.productQty.setText(Integer.toString(array[pos]));

            }

            callback.deletePressed();



        }
    });

Upvotes: 0

Views: 93

Answers (1)

Android android
Android android

Reputation: 53

try this on your onBindViewHolder(ViewHolder holder,int position) method

@Override
public void onBindViewHolder(final Helper holder, int position) {
    holder.setIsRecyclable(false);
}

Upvotes: 1

Related Questions