Salman Malik
Salman Malik

Reputation: 1118

ImageView does not replace previously used Drawable in RecyclerView Adapter

I am using ImageView inside my custom Adapter class. The problem is my Adapter has 2 image views inside and I am using a "placeholder image" as a default image on them but when I try to populate my RecyclerView and setImageResource() using Adapter's ViewHolder it simply goes behind the default "placeholder image" instead of overwriting it. I am quite new to both Java and Android App Development so I don't know if the setImageResource() works different with Adapters.

Here's my code:

public void onBindViewHolder(@NonNull ProductAdapter.ViewHolder holder, int position) {
        holder.itemView.setTag(product.get(position));

        holder.tvTitle.setText(product.get(position).getTitle());
        holder.tvDescription.setText(product.get(position).getDescription());

        //PROBLEM STARTS HERE
        //Set Status (getSale() returns bool)
        switch (product.get(position).getSale()?"sold":"available"){
            case "sold":
                holder.ivStatus.setImageResource(R.drawable.sold);
                break;
            case "available":
                holder.ivStatus.setImageResource(R.drawable.available);
                break;
        }

        //Set Product Image
        switch (product.get(position).getType()){
            case "Laptop":
                holder.ivProduct.setImageResource(R.drawable.laptop);
                break;
            case "LCD":
                holder.ivProduct.setImageResource(R.drawable.screen);
                break;
            case "USB":
                holder.ivProduct.setImageResource(R.drawable.memory);
                break;
            case "Hard Disk":
                holder.ivProduct.setImageResource(R.drawable.hdd);
                break;
        }


    }

In Both cases the switch-case works correctly and picks the right image resource but it simply places the image Resource behind placeholder image. how do I just overwrite the default image?

Upvotes: 1

Views: 228

Answers (1)

Zain
Zain

Reputation: 40830

The reason you see both images because you set both background and foreground images on the ImageView

To solve this remove android:foreground from both ImageViews and leave the placeholder in app:srcCompat

So your ImageView should look like:

<ImageView
    android:id="@+id/ivStatus"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_marginLeft="10dp"
    app:srcCompat="@drawable/placeholder" />

Upvotes: 1

Related Questions