spongyboss
spongyboss

Reputation: 291

Recyclerview selection inconsistent

I created a list using a recyclerview. Each item on the list has an icon that is clickable and changes colour when clicked. My problem is that whenever i select an icon, it changes not only that selected icon's colour but also the colour of the icon that is 8 indexes away. So if i select the icon at index 0, the icon at index 9 changes colour too. I don't know if I am making any sense.

Here is my ViewHolder that has the event handler

public class MenuItemHolder extends RecyclerView.ViewHolder
    {
        TextView menuItemTV;
        TextView menuItemPriceTV;
        ImageView cartIV;
        int selectedPosition;
        Boolean cartPressed = false;
        CardView itemCV;

        MenuItemHolder(View itemView)
        {
            super(itemView);
            menuItemTV = (TextView)itemView.findViewById(R.id.menuItem);
            menuItemPriceTV = (TextView)itemView.findViewById(R.id.itemPrice);
            itemCV = (CardView)itemView.findViewById(R.id.itemCV);
            cartIV = (ImageView) itemView.findViewById(R.id.cart);

            //Event handler for clicking on the whole card
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    selectedPosition = getPosition();
                    Log.i("Position", "Position = " + selectedPosition);
                }
            });

            cartIV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Log.i("Position", "Cart = " + menuItemTV.getText());
                    if(!cartPressed)
                    {
                        cartIV.setImageResource(R.drawable.ic_cart_blue);
                        cartPressed = true;
                    }
                    else {
                        cartIV.setImageResource(R.drawable.ic_cart_grey);
                        cartPressed = false;
                    }
                }
            });


        }
    }

Upvotes: 0

Views: 58

Answers (1)

Cody Caughlan
Cody Caughlan

Reputation: 32748

getPosition() is deprecated and the docs explain why and it might be the source of your problem as well:

This method is deprecated because its meaning is ambiguous due to the async handling of adapter updates. Please use getLayoutPosition() or getAdapterPosition() depending on your use case.

Source: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#getPosition()

Upvotes: 1

Related Questions