Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide an item from Recycler View on a particular condition?

I am using Firebase Recycler Adapter (Firebase UI Library) to populate Recycler View. I want to hide an item(row) on a condition. I have a LinearLayout containing a recycler view.

I set linear layout visibility to Gone in populateViewHolder() method of recycler view adapter.

@Override protected void populateViewHolder(UsersViewHolder viewHolder, User user, int position) {      if (user.getUserEmail().equals(Utils.decodeEmail(userEmail))) {         viewHolder.llMain.setVisibility(View.GONE);         return;     }      viewHolder.tvUserEmail.setText(user.getUserEmail()); } 

It hides the LinearLayout but the row remains there with empty space.

Is there any method I should override to overcome this or is there any way to achieve the result?

like image 965
Dhaval Avatar asked Dec 19 '16 13:12

Dhaval


2 Answers

In some cases changing only visibility attribute might still end up as allocated blank space (because of parent view's padding, margins, inner elements etc). Then changing height of the parent view helps:

holder.itemView.setVisibility(View.GONE);  holder.itemView.setLayoutParams(new RecyclerView.LayoutParams(0, 0)); 

Then be sure that in the condition that it should be visible, also set:

holder.itemView.setVisibility(View.VISIBLE); holder.itemView.setLayoutParams(new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); 

You need to do that because the viewHolder is recycled as you scroll, if you change properties as this and never return them to their natural state, other elements will be already hidden in the event they reuse the same view.

like image 108
incognito Avatar answered Sep 28 '22 06:09

incognito


You should hide all views or parent from UsersViewholder layout xml. You should hide entire viewholder or each view

Entire viewholder:

itemView.setVisibility(View.GONE); 

or each element:

view.setVisibility(View.GONE); 

But don't forget to set them VISIBLE otherwise, you will end up with some strange things from recycling

like image 24
Florescu Cătălin Avatar answered Sep 28 '22 07:09

Florescu Cătălin