ken
ken

Reputation: 2682

How to change element in layout dynamically based on position of recyclerview Android?

My data set have a element userId. I want to check if the position's userId is equal to userId of previous position,then a TextView set to GONE.

What I tried so far in onBindViewHolder:

final Item item = itemsArray.get(position);

if(position - 1 > -1){
   if(items.get(position-1).getUserId() == item.getUserId()) {
      holder.username.setVisibility(View.GONE);
   }
}

But end up,some of the item with same userId their username is gone,but some of them which userId is not same with the previous position's userId the username is gone too.

To make it clear,I attach some image to clearly show what I want.

This is what I want:

enter image description here

But end up,it become like below image,as you see item with different userId,the username also `gone.

enter image description here

So,my question is,how can I check the userId of previous item is same as userId of current position,so it wont end up to the second image I attached.

If have other solution please let me know as well.Thanks in advance.

Upvotes: 1

Views: 744

Answers (2)

Abu Yousuf
Abu Yousuf

Reputation: 6107

Use this code

 final Item item = itemsArray.get(position);
 holder.username.setVisibility(View.VISIBLE);
 if(position - 1 > -1){
   if(items.get(position-1).getUserId() == item.getUserId()) {
     holder.username.setVisibility(View.GONE);
  }else{
     holder.username.setVisibility(View.VISIBLE);
  }
}

As you are using RecyclerView so some view that's holder.username state is "GONE" is reused.

Upvotes: 1

Dima Kozhevin
Dima Kozhevin

Reputation: 3732

It is wrong way scan holders in an adapter and later changes it. You should prepare your data before you set data in the adapter. Change model of your data(for example, add field boolean isShowName to Item class)

Upvotes: 0

Related Questions