3

I have a RecyclerView that list data from server and it must show each row of data differently according to conditions. My data is list of a ticket messages. if a message is sent from the user, it's background must be colored gray and if it's from an agent it must be blue. in addition if this messages has an attachment it must show an download icon. here is my Adaptor code :

    @Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    if (holder.getItemViewType() == 0) {
        holder.itemView.setBackgroundResource(R.drawable.radius_background_gray);
        holder.ticketDate.setBackgroundResource(R.drawable.radius_background_light_gray);
    }
    if(ticket.get(position).getAttachment() != null)
        holder.ticketStatus.setImageResource(R.drawable.ic_attachment_black_24dp);

    holder.ticketTitle.setText(ticket.get(position).getAgentName() + " said :");

}

@Override
public int getItemViewType(int position) {
    if(ticket.get(position).getDirection().equals("out"))
        return 0;
    else return 1;
}

colors are being set correctly but when I use if clause to set an imageView for attachment a message that has no attachment and is null shows that attachment icon! Should I also check this condition in getItemType and not in onBindViewHolder?

Artin
  • 53
  • 7

3 Answers3

5

I can tell you that in my practice of working with RecyclerView it's always better to include an else clause to the if.

So, for example, in your case you could do something like this:

if(ticket.get(position).getAttachment() != null)
    holder.ticketStatus.setImageResource(R.drawable.ic_attachment_black_24dp);
else
    holder.ticketStatus.setVisibility(View.GONE);
Vendetta8247
  • 592
  • 1
  • 5
  • 30
  • please add XML of your view layout to the question and maybe even viewholder code as well. Are you sure that `getAttachment()` doesn't return null? – Vendetta8247 Aug 22 '18 at 09:11
  • for me, I also needed to set visibility to View.VISIBLE inside if statement, otherwise it was not working.....this might be helpful for somebody https://stackoverflow.com/a/34217561/7593595 – Martin.M Sep 20 '21 at 14:20
1
         if (getItemViewType(position) == 0) {
            holder.itemView.setBackgroundResource(R.drawable.radius_background_gray);
            holder.ticketDate.setBackgroundResource(R.drawable.radius_background_light_gray);
        }

Please try this.

PRATEEK BHARDWAJ
  • 2,364
  • 2
  • 21
  • 35
0

I solved my problem by checking my conditions in getItemType()

Artin
  • 53
  • 7