Codist
Codist

Reputation: 769

How to hide a child item in a recyclerView based on a condition?

First I used the following code but it did not show Perishable for items with the Food category.

            if(model.main_category=="Food"){
                holder.itemView.tv_dashboard_item_type.text="Perishable"
                
            }else{
                holder.itemView.tv_dashboard_item_type.visibility=View.GONE
            }

Then I used the following code and it showed "Perishable" for the first and the last item in the recyclerView where only the first item was under the 'Food' category, however, the last item in the recyclerView was not belong to 'Food' category. Then I changed the category of the item in the Firestore database from 'Food' to something else and the 'Perishable' is gone from both the first and last item in the recyclerView (where the last item is not food). With this code, items in between shows 'Perishable' correctly according to their category. What am I doing wrong here?

What I want is that it should show 'Perishable' for items belong to the 'Food' category and hide the view for other categories.

            if(model.main_category=="Food"){
                holder.itemView.tv_dashboard_item_type.text="Perishable"
                holder.itemView.tv_dashboard_item_type.visibility=View.VISIBLE
            }else{
//              holder.itemView.tv_dashboard_item_type.visibility=View.VISIBLE
            }

Thank you.

Upvotes: 1

Views: 415

Answers (2)

Masoud Fered
Masoud Fered

Reputation: 13

As Yash Joshi said, you have to define the condition in full Because the items are not recreated again, the same item changes its values according to your definition. If the full condition is not defined, the previous values remain on that item

Upvotes: 0

Yash Joshi
Yash Joshi

Reputation: 627

You're changing the visibility of the views but not defining the else condition properly. Sometimes the recyclerview doesn't refresh views properly because of that ambiguity.

Try this:

    if(model.main_category == "Food") {
        holder.itemView.tv_dashboard_item_type.visibility = View.VISIBLE
        holder.itemView.tv_dashboard_item_type.text = "Perishable"
    } else {
        holder.itemView.tv_dashboard_item_type.visibility = View.GONE
    }

Hope that works!

Upvotes: 3

Related Questions